clang  19.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/Randstruct.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/Builtins.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41 #include "clang/Sema/DeclSpec.h"
44 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Scope.h"
47 #include "clang/Sema/ScopeInfo.h"
48 #include "clang/Sema/SemaCUDA.h"
49 #include "clang/Sema/SemaHLSL.h"
51 #include "clang/Sema/SemaOpenMP.h"
52 #include "clang/Sema/SemaSYCL.h"
53 #include "clang/Sema/Template.h"
54 #include "llvm/ADT/STLForwardCompat.h"
55 #include "llvm/ADT/SmallString.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/TargetParser/Triple.h"
58 #include <algorithm>
59 #include <cstring>
60 #include <functional>
61 #include <optional>
62 #include <unordered_map>
63 
64 using namespace clang;
65 using namespace sema;
66 
68  if (OwnedType) {
69  Decl *Group[2] = { OwnedType, Ptr };
70  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
71  }
72 
73  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
74 }
75 
76 namespace {
77 
78 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
79  public:
80  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
81  bool AllowTemplates = false,
82  bool AllowNonTemplates = true)
83  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
84  AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
85  WantExpressionKeywords = false;
86  WantCXXNamedCasts = false;
87  WantRemainingKeywords = false;
88  }
89 
90  bool ValidateCandidate(const TypoCorrection &candidate) override {
91  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
92  if (!AllowInvalidDecl && ND->isInvalidDecl())
93  return false;
94 
95  if (getAsTypeTemplateDecl(ND))
96  return AllowTemplates;
97 
98  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
99  if (!IsType)
100  return false;
101 
102  if (AllowNonTemplates)
103  return true;
104 
105  // An injected-class-name of a class template (specialization) is valid
106  // as a template or as a non-template.
107  if (AllowTemplates) {
108  auto *RD = dyn_cast<CXXRecordDecl>(ND);
109  if (!RD || !RD->isInjectedClassName())
110  return false;
111  RD = cast<CXXRecordDecl>(RD->getDeclContext());
112  return RD->getDescribedClassTemplate() ||
113  isa<ClassTemplateSpecializationDecl>(RD);
114  }
115 
116  return false;
117  }
118 
119  return !WantClassName && candidate.isKeyword();
120  }
121 
122  std::unique_ptr<CorrectionCandidateCallback> clone() override {
123  return std::make_unique<TypeNameValidatorCCC>(*this);
124  }
125 
126  private:
127  bool AllowInvalidDecl;
128  bool WantClassName;
129  bool AllowTemplates;
130  bool AllowNonTemplates;
131 };
132 
133 } // end anonymous namespace
134 
135 namespace {
136 enum class UnqualifiedTypeNameLookupResult {
137  NotFound,
138  FoundNonType,
139  FoundType
140 };
141 } // end anonymous namespace
142 
143 /// Tries to perform unqualified lookup of the type decls in bases for
144 /// dependent class.
145 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
146 /// type decl, \a FoundType if only type decls are found.
147 static UnqualifiedTypeNameLookupResult
149  SourceLocation NameLoc,
150  const CXXRecordDecl *RD) {
151  if (!RD->hasDefinition())
152  return UnqualifiedTypeNameLookupResult::NotFound;
153  // Look for type decls in base classes.
154  UnqualifiedTypeNameLookupResult FoundTypeDecl =
155  UnqualifiedTypeNameLookupResult::NotFound;
156  for (const auto &Base : RD->bases()) {
157  const CXXRecordDecl *BaseRD = nullptr;
158  if (auto *BaseTT = Base.getType()->getAs<TagType>())
159  BaseRD = BaseTT->getAsCXXRecordDecl();
160  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
161  // Look for type decls in dependent base classes that have known primary
162  // templates.
163  if (!TST || !TST->isDependentType())
164  continue;
165  auto *TD = TST->getTemplateName().getAsTemplateDecl();
166  if (!TD)
167  continue;
168  if (auto *BasePrimaryTemplate =
169  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
170  if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
171  BaseRD = BasePrimaryTemplate;
172  else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
174  CTD->findPartialSpecialization(Base.getType()))
175  if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
176  BaseRD = PS;
177  }
178  }
179  }
180  if (BaseRD) {
181  for (NamedDecl *ND : BaseRD->lookup(&II)) {
182  if (!isa<TypeDecl>(ND))
183  return UnqualifiedTypeNameLookupResult::FoundNonType;
184  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
185  }
186  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
187  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
188  case UnqualifiedTypeNameLookupResult::FoundNonType:
189  return UnqualifiedTypeNameLookupResult::FoundNonType;
190  case UnqualifiedTypeNameLookupResult::FoundType:
191  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
192  break;
193  case UnqualifiedTypeNameLookupResult::NotFound:
194  break;
195  }
196  }
197  }
198  }
199 
200  return FoundTypeDecl;
201 }
202 
204  const IdentifierInfo &II,
205  SourceLocation NameLoc) {
206  // Lookup in the parent class template context, if any.
207  const CXXRecordDecl *RD = nullptr;
208  UnqualifiedTypeNameLookupResult FoundTypeDecl =
209  UnqualifiedTypeNameLookupResult::NotFound;
210  for (DeclContext *DC = S.CurContext;
211  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
212  DC = DC->getParent()) {
213  // Look for type decls in dependent base classes that have known primary
214  // templates.
215  RD = dyn_cast<CXXRecordDecl>(DC);
216  if (RD && RD->getDescribedClassTemplate())
217  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
218  }
219  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
220  return nullptr;
221 
222  // We found some types in dependent base classes. Recover as if the user
223  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
224  // lookup during template instantiation.
225  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
226 
227  ASTContext &Context = S.Context;
228  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
229  cast<Type>(Context.getRecordType(RD)));
230  QualType T =
232 
233  CXXScopeSpec SS;
234  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
235 
236  TypeLocBuilder Builder;
237  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
238  DepTL.setNameLoc(NameLoc);
240  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
241  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
242 }
243 
244 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
246  SourceLocation NameLoc,
247  bool WantNontrivialTypeSourceInfo = true) {
248  switch (T->getTypeClass()) {
249  case Type::DeducedTemplateSpecialization:
250  case Type::Enum:
251  case Type::InjectedClassName:
252  case Type::Record:
253  case Type::Typedef:
254  case Type::UnresolvedUsing:
255  case Type::Using:
256  break;
257  // These can never be qualified so an ElaboratedType node
258  // would carry no additional meaning.
259  case Type::ObjCInterface:
260  case Type::ObjCTypeParam:
261  case Type::TemplateTypeParm:
262  return ParsedType::make(T);
263  default:
264  llvm_unreachable("Unexpected Type Class");
265  }
266 
267  if (!SS || SS->isEmpty())
269  ElaboratedTypeKeyword::None, nullptr, T, nullptr));
270 
272  if (!WantNontrivialTypeSourceInfo)
273  return ParsedType::make(ElTy);
274 
275  TypeLocBuilder Builder;
276  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
277  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
280  return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
281 }
282 
283 /// If the identifier refers to a type name within this scope,
284 /// return the declaration of that type.
285 ///
286 /// This routine performs ordinary name lookup of the identifier II
287 /// within the given scope, with optional C++ scope specifier SS, to
288 /// determine whether the name refers to a type. If so, returns an
289 /// opaque pointer (actually a QualType) corresponding to that
290 /// type. Otherwise, returns NULL.
292  Scope *S, CXXScopeSpec *SS, bool isClassName,
293  bool HasTrailingDot, ParsedType ObjectTypePtr,
294  bool IsCtorOrDtorName,
295  bool WantNontrivialTypeSourceInfo,
296  bool IsClassTemplateDeductionContext,
297  ImplicitTypenameContext AllowImplicitTypename,
298  IdentifierInfo **CorrectedII) {
299  // FIXME: Consider allowing this outside C++1z mode as an extension.
300  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
301  getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
302  !isClassName && !HasTrailingDot;
303 
304  // Determine where we will perform name lookup.
305  DeclContext *LookupCtx = nullptr;
306  if (ObjectTypePtr) {
307  QualType ObjectType = ObjectTypePtr.get();
308  if (ObjectType->isRecordType())
309  LookupCtx = computeDeclContext(ObjectType);
310  } else if (SS && SS->isNotEmpty()) {
311  LookupCtx = computeDeclContext(*SS, false);
312 
313  if (!LookupCtx) {
314  if (isDependentScopeSpecifier(*SS)) {
315  // C++ [temp.res]p3:
316  // A qualified-id that refers to a type and in which the
317  // nested-name-specifier depends on a template-parameter (14.6.2)
318  // shall be prefixed by the keyword typename to indicate that the
319  // qualified-id denotes a type, forming an
320  // elaborated-type-specifier (7.1.5.3).
321  //
322  // We therefore do not perform any name lookup if the result would
323  // refer to a member of an unknown specialization.
324  // In C++2a, in several contexts a 'typename' is not required. Also
325  // allow this as an extension.
326  if (AllowImplicitTypename == ImplicitTypenameContext::No &&
327  !isClassName && !IsCtorOrDtorName)
328  return nullptr;
329  bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
330  if (IsImplicitTypename) {
331  SourceLocation QualifiedLoc = SS->getRange().getBegin();
332  if (getLangOpts().CPlusPlus20)
333  Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
334  else
335  Diag(QualifiedLoc, diag::ext_implicit_typename)
336  << SS->getScopeRep() << II.getName()
337  << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
338  }
339 
340  // We know from the grammar that this name refers to a type,
341  // so build a dependent node to describe the type.
342  if (WantNontrivialTypeSourceInfo)
343  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
344  (ImplicitTypenameContext)IsImplicitTypename)
345  .get();
346 
347  NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
348  QualType T = CheckTypenameType(
349  IsImplicitTypename ? ElaboratedTypeKeyword::Typename
351  SourceLocation(), QualifierLoc, II, NameLoc);
352  return ParsedType::make(T);
353  }
354 
355  return nullptr;
356  }
357 
358  if (!LookupCtx->isDependentContext() &&
359  RequireCompleteDeclContext(*SS, LookupCtx))
360  return nullptr;
361  }
362 
363  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
364  // lookup for class-names.
365  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
366  LookupOrdinaryName;
367  LookupResult Result(*this, &II, NameLoc, Kind);
368  if (LookupCtx) {
369  // Perform "qualified" name lookup into the declaration context we
370  // computed, which is either the type of the base of a member access
371  // expression or the declaration context associated with a prior
372  // nested-name-specifier.
373  LookupQualifiedName(Result, LookupCtx);
374 
375  if (ObjectTypePtr && Result.empty()) {
376  // C++ [basic.lookup.classref]p3:
377  // If the unqualified-id is ~type-name, the type-name is looked up
378  // in the context of the entire postfix-expression. If the type T of
379  // the object expression is of a class type C, the type-name is also
380  // looked up in the scope of class C. At least one of the lookups shall
381  // find a name that refers to (possibly cv-qualified) T.
382  LookupName(Result, S);
383  }
384  } else {
385  // Perform unqualified name lookup.
386  LookupName(Result, S);
387 
388  // For unqualified lookup in a class template in MSVC mode, look into
389  // dependent base classes where the primary class template is known.
390  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
391  if (ParsedType TypeInBase =
392  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
393  return TypeInBase;
394  }
395  }
396 
397  NamedDecl *IIDecl = nullptr;
398  UsingShadowDecl *FoundUsingShadow = nullptr;
399  switch (Result.getResultKind()) {
401  if (CorrectedII) {
402  TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
403  AllowDeducedTemplate);
404  TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
405  S, SS, CCC, CTK_ErrorRecovery);
406  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
407  TemplateTy Template;
408  bool MemberOfUnknownSpecialization;
410  TemplateName.setIdentifier(NewII, NameLoc);
411  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
412  CXXScopeSpec NewSS, *NewSSPtr = SS;
413  if (SS && NNS) {
414  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
415  NewSSPtr = &NewSS;
416  }
417  if (Correction && (NNS || NewII != &II) &&
418  // Ignore a correction to a template type as the to-be-corrected
419  // identifier is not a template (typo correction for template names
420  // is handled elsewhere).
421  !(getLangOpts().CPlusPlus && NewSSPtr &&
422  isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
423  Template, MemberOfUnknownSpecialization))) {
424  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
425  isClassName, HasTrailingDot, ObjectTypePtr,
426  IsCtorOrDtorName,
427  WantNontrivialTypeSourceInfo,
428  IsClassTemplateDeductionContext);
429  if (Ty) {
430  diagnoseTypo(Correction,
431  PDiag(diag::err_unknown_type_or_class_name_suggest)
432  << Result.getLookupName() << isClassName);
433  if (SS && NNS)
434  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
435  *CorrectedII = NewII;
436  return Ty;
437  }
438  }
439  }
440  Result.suppressDiagnostics();
441  return nullptr;
443  if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
445  SS->getScopeRep(), &II);
446  TypeLocBuilder TLB;
449  TL.setQualifierLoc(SS->getWithLocInContext(Context));
450  TL.setNameLoc(NameLoc);
451  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
452  }
453  [[fallthrough]];
456  Result.suppressDiagnostics();
457  return nullptr;
458 
460  // Recover from type-hiding ambiguities by hiding the type. We'll
461  // do the lookup again when looking for an object, and we can
462  // diagnose the error then. If we don't do this, then the error
463  // about hiding the type will be immediately followed by an error
464  // that only makes sense if the identifier was treated like a type.
465  if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
466  Result.suppressDiagnostics();
467  return nullptr;
468  }
469 
470  // Look to see if we have a type anywhere in the list of results.
471  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
472  Res != ResEnd; ++Res) {
473  NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
474  if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
475  RealRes) ||
476  (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
477  if (!IIDecl ||
478  // Make the selection of the recovery decl deterministic.
479  RealRes->getLocation() < IIDecl->getLocation()) {
480  IIDecl = RealRes;
481  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
482  }
483  }
484  }
485 
486  if (!IIDecl) {
487  // None of the entities we found is a type, so there is no way
488  // to even assume that the result is a type. In this case, don't
489  // complain about the ambiguity. The parser will either try to
490  // perform this lookup again (e.g., as an object name), which
491  // will produce the ambiguity, or will complain that it expected
492  // a type name.
493  Result.suppressDiagnostics();
494  return nullptr;
495  }
496 
497  // We found a type within the ambiguous lookup; diagnose the
498  // ambiguity and then return that type. This might be the right
499  // answer, or it might not be, but it suppresses any attempt to
500  // perform the name lookup again.
501  break;
502 
503  case LookupResult::Found:
504  IIDecl = Result.getFoundDecl();
505  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
506  break;
507  }
508 
509  assert(IIDecl && "Didn't find decl");
510 
511  QualType T;
512  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
513  // C++ [class.qual]p2: A lookup that would find the injected-class-name
514  // instead names the constructors of the class, except when naming a class.
515  // This is ill-formed when we're not actually forming a ctor or dtor name.
516  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
517  auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
518  if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
519  FoundRD->isInjectedClassName() &&
520  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
521  Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
522  << &II << /*Type*/1;
523 
524  DiagnoseUseOfDecl(IIDecl, NameLoc);
525 
526  T = Context.getTypeDeclType(TD);
527  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
528  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
529  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
530  if (!HasTrailingDot)
531  T = Context.getObjCInterfaceType(IDecl);
532  FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
533  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
534  (void)DiagnoseUseOfDecl(UD, NameLoc);
535  // Recover with 'int'
536  return ParsedType::make(Context.IntTy);
537  } else if (AllowDeducedTemplate) {
538  if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
539  assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
540  TemplateName Template =
541  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
542  T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
543  false);
544  // Don't wrap in a further UsingType.
545  FoundUsingShadow = nullptr;
546  }
547  }
548 
549  if (T.isNull()) {
550  // If it's not plausibly a type, suppress diagnostics.
551  Result.suppressDiagnostics();
552  return nullptr;
553  }
554 
555  if (FoundUsingShadow)
556  T = Context.getUsingType(FoundUsingShadow, T);
557 
558  return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
559 }
560 
561 // Builds a fake NNS for the given decl context.
562 static NestedNameSpecifier *
564  for (;; DC = DC->getLookupParent()) {
565  DC = DC->getPrimaryContext();
566  auto *ND = dyn_cast<NamespaceDecl>(DC);
567  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
568  return NestedNameSpecifier::Create(Context, nullptr, ND);
569  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
570  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
571  RD->getTypeForDecl());
572  else if (isa<TranslationUnitDecl>(DC))
573  return NestedNameSpecifier::GlobalSpecifier(Context);
574  }
575  llvm_unreachable("something isn't in TU scope?");
576 }
577 
578 /// Find the parent class with dependent bases of the innermost enclosing method
579 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
580 /// up allowing unqualified dependent type names at class-level, which MSVC
581 /// correctly rejects.
582 static const CXXRecordDecl *
584  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
585  DC = DC->getPrimaryContext();
586  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
587  if (MD->getParent()->hasAnyDependentBases())
588  return MD->getParent();
589  }
590  return nullptr;
591 }
592 
594  SourceLocation NameLoc,
595  bool IsTemplateTypeArg) {
596  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
597 
598  NestedNameSpecifier *NNS = nullptr;
599  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
600  // If we weren't able to parse a default template argument, delay lookup
601  // until instantiation time by making a non-dependent DependentTypeName. We
602  // pretend we saw a NestedNameSpecifier referring to the current scope, and
603  // lookup is retried.
604  // FIXME: This hurts our diagnostic quality, since we get errors like "no
605  // type named 'Foo' in 'current_namespace'" when the user didn't write any
606  // name specifiers.
607  NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
608  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
609  } else if (const CXXRecordDecl *RD =
611  // Build a DependentNameType that will perform lookup into RD at
612  // instantiation time.
613  NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
614  RD->getTypeForDecl());
615 
616  // Diagnose that this identifier was undeclared, and retry the lookup during
617  // template instantiation.
618  Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
619  << RD;
620  } else {
621  // This is not a situation that we should recover from.
622  return ParsedType();
623  }
624 
625  QualType T =
627 
628  // Build type location information. We synthesized the qualifier, so we have
629  // to build a fake NestedNameSpecifierLoc.
630  NestedNameSpecifierLocBuilder NNSLocBuilder;
631  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
632  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
633 
634  TypeLocBuilder Builder;
635  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
636  DepTL.setNameLoc(NameLoc);
638  DepTL.setQualifierLoc(QualifierLoc);
639  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
640 }
641 
642 /// isTagName() - This method is called *for error recovery purposes only*
643 /// to determine if the specified name is a valid tag name ("struct foo"). If
644 /// so, this returns the TST for the tag corresponding to it (TST_enum,
645 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
646 /// cases in C where the user forgot to specify the tag.
648  // Do a tag name lookup in this scope.
649  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
650  LookupName(R, S, false);
653  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
654  switch (TD->getTagKind()) {
655  case TagTypeKind::Struct:
656  return DeclSpec::TST_struct;
659  case TagTypeKind::Union:
660  return DeclSpec::TST_union;
661  case TagTypeKind::Class:
662  return DeclSpec::TST_class;
663  case TagTypeKind::Enum:
664  return DeclSpec::TST_enum;
665  }
666  }
667 
669 }
670 
671 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
672 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
673 /// then downgrade the missing typename error to a warning.
674 /// This is needed for MSVC compatibility; Example:
675 /// @code
676 /// template<class T> class A {
677 /// public:
678 /// typedef int TYPE;
679 /// };
680 /// template<class T> class B : public A<T> {
681 /// public:
682 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
683 /// };
684 /// @endcode
686  if (CurContext->isRecord()) {
688  return true;
689 
690  const Type *Ty = SS->getScopeRep()->getAsType();
691 
692  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
693  for (const auto &Base : RD->bases())
694  if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
695  return true;
696  return S->isFunctionPrototypeScope();
697  }
698  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
699 }
700 
702  SourceLocation IILoc,
703  Scope *S,
704  CXXScopeSpec *SS,
705  ParsedType &SuggestedType,
706  bool IsTemplateName) {
707  // Don't report typename errors for editor placeholders.
708  if (II->isEditorPlaceholder())
709  return;
710  // We don't have anything to suggest (yet).
711  SuggestedType = nullptr;
712 
713  // There may have been a typo in the name of the type. Look up typo
714  // results, in case we have something that we can suggest.
715  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
716  /*AllowTemplates=*/IsTemplateName,
717  /*AllowNonTemplates=*/!IsTemplateName);
718  if (TypoCorrection Corrected =
719  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
720  CCC, CTK_ErrorRecovery)) {
721  // FIXME: Support error recovery for the template-name case.
722  bool CanRecover = !IsTemplateName;
723  if (Corrected.isKeyword()) {
724  // We corrected to a keyword.
725  diagnoseTypo(Corrected,
726  PDiag(IsTemplateName ? diag::err_no_template_suggest
727  : diag::err_unknown_typename_suggest)
728  << II);
729  II = Corrected.getCorrectionAsIdentifierInfo();
730  } else {
731  // We found a similarly-named type or interface; suggest that.
732  if (!SS || !SS->isSet()) {
733  diagnoseTypo(Corrected,
734  PDiag(IsTemplateName ? diag::err_no_template_suggest
735  : diag::err_unknown_typename_suggest)
736  << II, CanRecover);
737  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
738  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
739  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
740  II->getName().equals(CorrectedStr);
741  diagnoseTypo(Corrected,
742  PDiag(IsTemplateName
743  ? diag::err_no_member_template_suggest
744  : diag::err_unknown_nested_typename_suggest)
745  << II << DC << DroppedSpecifier << SS->getRange(),
746  CanRecover);
747  } else {
748  llvm_unreachable("could not have corrected a typo here");
749  }
750 
751  if (!CanRecover)
752  return;
753 
754  CXXScopeSpec tmpSS;
755  if (Corrected.getCorrectionSpecifier())
756  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
757  SourceRange(IILoc));
758  // FIXME: Support class template argument deduction here.
759  SuggestedType =
760  getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
761  tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
762  /*IsCtorOrDtorName=*/false,
763  /*WantNontrivialTypeSourceInfo=*/true);
764  }
765  return;
766  }
767 
768  if (getLangOpts().CPlusPlus && !IsTemplateName) {
769  // See if II is a class template that the user forgot to pass arguments to.
770  UnqualifiedId Name;
771  Name.setIdentifier(II, IILoc);
772  CXXScopeSpec EmptySS;
773  TemplateTy TemplateResult;
774  bool MemberOfUnknownSpecialization;
775  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
776  Name, nullptr, true, TemplateResult,
777  MemberOfUnknownSpecialization) == TNK_Type_template) {
778  diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
779  return;
780  }
781  }
782 
783  // FIXME: Should we move the logic that tries to recover from a missing tag
784  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
785 
786  if (!SS || (!SS->isSet() && !SS->isInvalid()))
787  Diag(IILoc, IsTemplateName ? diag::err_no_template
788  : diag::err_unknown_typename)
789  << II;
790  else if (DeclContext *DC = computeDeclContext(*SS, false))
791  Diag(IILoc, IsTemplateName ? diag::err_no_member_template
792  : diag::err_typename_nested_not_found)
793  << II << DC << SS->getRange();
794  else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
795  SuggestedType =
796  ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
797  } else if (isDependentScopeSpecifier(*SS)) {
798  unsigned DiagID = diag::err_typename_missing;
799  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
800  DiagID = diag::ext_typename_missing;
801 
802  Diag(SS->getRange().getBegin(), DiagID)
803  << SS->getScopeRep() << II->getName()
804  << SourceRange(SS->getRange().getBegin(), IILoc)
805  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
806  SuggestedType = ActOnTypenameType(S, SourceLocation(),
807  *SS, *II, IILoc).get();
808  } else {
809  assert(SS && SS->isInvalid() &&
810  "Invalid scope specifier has already been diagnosed");
811  }
812 }
813 
814 /// Determine whether the given result set contains either a type name
815 /// or
816 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
817  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
818  NextToken.is(tok::less);
819 
820  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
821  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
822  return true;
823 
824  if (CheckTemplate && isa<TemplateDecl>(*I))
825  return true;
826  }
827 
828  return false;
829 }
830 
831 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
832  Scope *S, CXXScopeSpec &SS,
833  IdentifierInfo *&Name,
834  SourceLocation NameLoc) {
835  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
836  SemaRef.LookupParsedName(R, S, &SS);
837  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
838  StringRef FixItTagName;
839  switch (Tag->getTagKind()) {
840  case TagTypeKind::Class:
841  FixItTagName = "class ";
842  break;
843 
844  case TagTypeKind::Enum:
845  FixItTagName = "enum ";
846  break;
847 
848  case TagTypeKind::Struct:
849  FixItTagName = "struct ";
850  break;
851 
853  FixItTagName = "__interface ";
854  break;
855 
856  case TagTypeKind::Union:
857  FixItTagName = "union ";
858  break;
859  }
860 
861  StringRef TagName = FixItTagName.drop_back();
862  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
863  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
864  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
865 
866  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
867  I != IEnd; ++I)
868  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
869  << Name << TagName;
870 
871  // Replace lookup results with just the tag decl.
872  Result.clear(Sema::LookupTagName);
873  SemaRef.LookupParsedName(Result, S, &SS);
874  return true;
875  }
876 
877  return false;
878 }
879 
881  IdentifierInfo *&Name,
882  SourceLocation NameLoc,
883  const Token &NextToken,
885  DeclarationNameInfo NameInfo(Name, NameLoc);
886  ObjCMethodDecl *CurMethod = getCurMethodDecl();
887 
888  assert(NextToken.isNot(tok::coloncolon) &&
889  "parse nested name specifiers before calling ClassifyName");
890  if (getLangOpts().CPlusPlus && SS.isSet() &&
891  isCurrentClassName(*Name, S, &SS)) {
892  // Per [class.qual]p2, this names the constructors of SS, not the
893  // injected-class-name. We don't have a classification for that.
894  // There's not much point caching this result, since the parser
895  // will reject it later.
897  }
898 
899  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
900  LookupParsedName(Result, S, &SS, !CurMethod);
901 
902  if (SS.isInvalid())
903  return NameClassification::Error();
904 
905  // For unqualified lookup in a class template in MSVC mode, look into
906  // dependent base classes where the primary class template is known.
907  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
908  if (ParsedType TypeInBase =
909  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
910  return TypeInBase;
911  }
912 
913  // Perform lookup for Objective-C instance variables (including automatically
914  // synthesized instance variables), if we're in an Objective-C method.
915  // FIXME: This lookup really, really needs to be folded in to the normal
916  // unqualified lookup mechanism.
917  if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
918  DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
919  if (Ivar.isInvalid())
920  return NameClassification::Error();
921  if (Ivar.isUsable())
922  return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
923 
924  // We defer builtin creation until after ivar lookup inside ObjC methods.
925  if (Result.empty())
926  LookupBuiltin(Result);
927  }
928 
929  bool SecondTry = false;
930  bool IsFilteredTemplateName = false;
931 
932 Corrected:
933  switch (Result.getResultKind()) {
935  // If an unqualified-id is followed by a '(', then we have a function
936  // call.
937  if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
938  // In C++, this is an ADL-only call.
939  // FIXME: Reference?
940  if (getLangOpts().CPlusPlus)
941  return NameClassification::UndeclaredNonType();
942 
943  // C90 6.3.2.2:
944  // If the expression that precedes the parenthesized argument list in a
945  // function call consists solely of an identifier, and if no
946  // declaration is visible for this identifier, the identifier is
947  // implicitly declared exactly as if, in the innermost block containing
948  // the function call, the declaration
949  //
950  // extern int identifier ();
951  //
952  // appeared.
953  //
954  // We also allow this in C99 as an extension. However, this is not
955  // allowed in all language modes as functions without prototypes may not
956  // be supported.
957  if (getLangOpts().implicitFunctionsAllowed()) {
958  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
959  return NameClassification::NonType(D);
960  }
961  }
962 
963  if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
964  // In C++20 onwards, this could be an ADL-only call to a function
965  // template, and we're required to assume that this is a template name.
966  //
967  // FIXME: Find a way to still do typo correction in this case.
968  TemplateName Template =
969  Context.getAssumedTemplateName(NameInfo.getName());
970  return NameClassification::UndeclaredTemplate(Template);
971  }
972 
973  // In C, we first see whether there is a tag type by the same name, in
974  // which case it's likely that the user just forgot to write "enum",
975  // "struct", or "union".
976  if (!getLangOpts().CPlusPlus && !SecondTry &&
977  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
978  break;
979  }
980 
981  // Perform typo correction to determine if there is another name that is
982  // close to this name.
983  if (!SecondTry && CCC) {
984  SecondTry = true;
985  if (TypoCorrection Corrected =
986  CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
987  &SS, *CCC, CTK_ErrorRecovery)) {
988  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
989  unsigned QualifiedDiag = diag::err_no_member_suggest;
990 
991  NamedDecl *FirstDecl = Corrected.getFoundDecl();
992  NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
993  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
994  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
995  UnqualifiedDiag = diag::err_no_template_suggest;
996  QualifiedDiag = diag::err_no_member_template_suggest;
997  } else if (UnderlyingFirstDecl &&
998  (isa<TypeDecl>(UnderlyingFirstDecl) ||
999  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1000  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1001  UnqualifiedDiag = diag::err_unknown_typename_suggest;
1002  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1003  }
1004 
1005  if (SS.isEmpty()) {
1006  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1007  } else {// FIXME: is this even reachable? Test it.
1008  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1009  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1010  Name->getName().equals(CorrectedStr);
1011  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1012  << Name << computeDeclContext(SS, false)
1013  << DroppedSpecifier << SS.getRange());
1014  }
1015 
1016  // Update the name, so that the caller has the new name.
1017  Name = Corrected.getCorrectionAsIdentifierInfo();
1018 
1019  // Typo correction corrected to a keyword.
1020  if (Corrected.isKeyword())
1021  return Name;
1022 
1023  // Also update the LookupResult...
1024  // FIXME: This should probably go away at some point
1025  Result.clear();
1026  Result.setLookupName(Corrected.getCorrection());
1027  if (FirstDecl)
1028  Result.addDecl(FirstDecl);
1029 
1030  // If we found an Objective-C instance variable, let
1031  // LookupInObjCMethod build the appropriate expression to
1032  // reference the ivar.
1033  // FIXME: This is a gross hack.
1034  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1035  DeclResult R =
1036  LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1037  if (R.isInvalid())
1038  return NameClassification::Error();
1039  if (R.isUsable())
1040  return NameClassification::NonType(Ivar);
1041  }
1042 
1043  goto Corrected;
1044  }
1045  }
1046 
1047  // We failed to correct; just fall through and let the parser deal with it.
1048  Result.suppressDiagnostics();
1049  return NameClassification::Unknown();
1050 
1052  // We performed name lookup into the current instantiation, and there were
1053  // dependent bases, so we treat this result the same way as any other
1054  // dependent nested-name-specifier.
1055 
1056  // C++ [temp.res]p2:
1057  // A name used in a template declaration or definition and that is
1058  // dependent on a template-parameter is assumed not to name a type
1059  // unless the applicable name lookup finds a type name or the name is
1060  // qualified by the keyword typename.
1061  //
1062  // FIXME: If the next token is '<', we might want to ask the parser to
1063  // perform some heroics to see if we actually have a
1064  // template-argument-list, which would indicate a missing 'template'
1065  // keyword here.
1066  return NameClassification::DependentNonType();
1067  }
1068 
1069  case LookupResult::Found:
1072  break;
1073 
1075  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076  hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1077  /*AllowDependent=*/false)) {
1078  // C++ [temp.local]p3:
1079  // A lookup that finds an injected-class-name (10.2) can result in an
1080  // ambiguity in certain cases (for example, if it is found in more than
1081  // one base class). If all of the injected-class-names that are found
1082  // refer to specializations of the same class template, and if the name
1083  // is followed by a template-argument-list, the reference refers to the
1084  // class template itself and not a specialization thereof, and is not
1085  // ambiguous.
1086  //
1087  // This filtering can make an ambiguous result into an unambiguous one,
1088  // so try again after filtering out template names.
1089  FilterAcceptableTemplateNames(Result);
1090  if (!Result.isAmbiguous()) {
1091  IsFilteredTemplateName = true;
1092  break;
1093  }
1094  }
1095 
1096  // Diagnose the ambiguity and return an error.
1097  return NameClassification::Error();
1098  }
1099 
1100  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1101  (IsFilteredTemplateName ||
1102  hasAnyAcceptableTemplateNames(
1103  Result, /*AllowFunctionTemplates=*/true,
1104  /*AllowDependent=*/false,
1105  /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1106  getLangOpts().CPlusPlus20))) {
1107  // C++ [temp.names]p3:
1108  // After name lookup (3.4) finds that a name is a template-name or that
1109  // an operator-function-id or a literal- operator-id refers to a set of
1110  // overloaded functions any member of which is a function template if
1111  // this is followed by a <, the < is always taken as the delimiter of a
1112  // template-argument-list and never as the less-than operator.
1113  // C++2a [temp.names]p2:
1114  // A name is also considered to refer to a template if it is an
1115  // unqualified-id followed by a < and name lookup finds either one
1116  // or more functions or finds nothing.
1117  if (!IsFilteredTemplateName)
1118  FilterAcceptableTemplateNames(Result);
1119 
1120  bool IsFunctionTemplate;
1121  bool IsVarTemplate;
1122  TemplateName Template;
1123  if (Result.end() - Result.begin() > 1) {
1124  IsFunctionTemplate = true;
1125  Template = Context.getOverloadedTemplateName(Result.begin(),
1126  Result.end());
1127  } else if (!Result.empty()) {
1128  auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1129  *Result.begin(), /*AllowFunctionTemplates=*/true,
1130  /*AllowDependent=*/false));
1131  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1132  IsVarTemplate = isa<VarTemplateDecl>(TD);
1133 
1134  UsingShadowDecl *FoundUsingShadow =
1135  dyn_cast<UsingShadowDecl>(*Result.begin());
1136  assert(!FoundUsingShadow ||
1137  TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1138  Template =
1139  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1140  if (SS.isNotEmpty())
1141  Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1142  /*TemplateKeyword=*/false,
1143  Template);
1144  } else {
1145  // All results were non-template functions. This is a function template
1146  // name.
1147  IsFunctionTemplate = true;
1148  Template = Context.getAssumedTemplateName(NameInfo.getName());
1149  }
1150 
1151  if (IsFunctionTemplate) {
1152  // Function templates always go through overload resolution, at which
1153  // point we'll perform the various checks (e.g., accessibility) we need
1154  // to based on which function we selected.
1155  Result.suppressDiagnostics();
1156 
1157  return NameClassification::FunctionTemplate(Template);
1158  }
1159 
1160  return IsVarTemplate ? NameClassification::VarTemplate(Template)
1161  : NameClassification::TypeTemplate(Template);
1162  }
1163 
1164  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1165  QualType T = Context.getTypeDeclType(Type);
1166  if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1167  T = Context.getUsingType(USD, T);
1168  return buildNamedType(*this, &SS, T, NameLoc);
1169  };
1170 
1171  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1172  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1173  DiagnoseUseOfDecl(Type, NameLoc);
1174  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1175  return BuildTypeFor(Type, *Result.begin());
1176  }
1177 
1178  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1179  if (!Class) {
1180  // FIXME: It's unfortunate that we don't have a Type node for handling this.
1181  if (ObjCCompatibleAliasDecl *Alias =
1182  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1183  Class = Alias->getClassInterface();
1184  }
1185 
1186  if (Class) {
1187  DiagnoseUseOfDecl(Class, NameLoc);
1188 
1189  if (NextToken.is(tok::period)) {
1190  // Interface. <something> is parsed as a property reference expression.
1191  // Just return "unknown" as a fall-through for now.
1192  Result.suppressDiagnostics();
1193  return NameClassification::Unknown();
1194  }
1195 
1196  QualType T = Context.getObjCInterfaceType(Class);
1197  return ParsedType::make(T);
1198  }
1199 
1200  if (isa<ConceptDecl>(FirstDecl)) {
1201  // We want to preserve the UsingShadowDecl for concepts.
1202  if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1203  return NameClassification::Concept(TemplateName(USD));
1204  return NameClassification::Concept(
1205  TemplateName(cast<TemplateDecl>(FirstDecl)));
1206  }
1207 
1208  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1209  (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1210  return NameClassification::Error();
1211  }
1212 
1213  // We can have a type template here if we're classifying a template argument.
1214  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1215  !isa<VarTemplateDecl>(FirstDecl))
1216  return NameClassification::TypeTemplate(
1217  TemplateName(cast<TemplateDecl>(FirstDecl)));
1218 
1219  // Check for a tag type hidden by a non-type decl in a few cases where it
1220  // seems likely a type is wanted instead of the non-type that was found.
1221  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1222  if ((NextToken.is(tok::identifier) ||
1223  (NextIsOp &&
1224  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1225  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1226  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1227  DiagnoseUseOfDecl(Type, NameLoc);
1228  return BuildTypeFor(Type, *Result.begin());
1229  }
1230 
1231  // If we already know which single declaration is referenced, just annotate
1232  // that declaration directly. Defer resolving even non-overloaded class
1233  // member accesses, as we need to defer certain access checks until we know
1234  // the context.
1235  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1236  if (Result.isSingleResult() && !ADL &&
1237  (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1238  return NameClassification::NonType(Result.getRepresentativeDecl());
1239 
1240  // Otherwise, this is an overload set that we will need to resolve later.
1241  Result.suppressDiagnostics();
1242  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1243  Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1244  Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1245  /*KnownDependent=*/false));
1246 }
1247 
1248 ExprResult
1250  SourceLocation NameLoc) {
1251  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1252  CXXScopeSpec SS;
1253  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1254  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1255 }
1256 
1257 ExprResult
1259  IdentifierInfo *Name,
1260  SourceLocation NameLoc,
1261  bool IsAddressOfOperand) {
1262  DeclarationNameInfo NameInfo(Name, NameLoc);
1263  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1264  NameInfo, IsAddressOfOperand,
1265  /*TemplateArgs=*/nullptr);
1266 }
1267 
1269  NamedDecl *Found,
1270  SourceLocation NameLoc,
1271  const Token &NextToken) {
1272  if (getCurMethodDecl() && SS.isEmpty())
1273  if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1274  return BuildIvarRefExpr(S, NameLoc, Ivar);
1275 
1276  // Reconstruct the lookup result.
1277  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1278  Result.addDecl(Found);
1279  Result.resolveKind();
1280 
1281  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1282  return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1283 }
1284 
1286  // For an implicit class member access, transform the result into a member
1287  // access expression if necessary.
1288  auto *ULE = cast<UnresolvedLookupExpr>(E);
1289  if ((*ULE->decls_begin())->isCXXClassMember()) {
1290  CXXScopeSpec SS;
1291  SS.Adopt(ULE->getQualifierLoc());
1292 
1293  // Reconstruct the lookup result.
1294  LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1295  LookupOrdinaryName);
1296  Result.setNamingClass(ULE->getNamingClass());
1297  for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1298  Result.addDecl(*I, I.getAccess());
1299  Result.resolveKind();
1300  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1301  nullptr, S);
1302  }
1303 
1304  // Otherwise, this is already in the form we needed, and no further checks
1305  // are necessary.
1306  return ULE;
1307 }
1308 
1311  auto *TD = Name.getAsTemplateDecl();
1312  if (!TD)
1313  return TemplateNameKindForDiagnostics::DependentTemplate;
1314  if (isa<ClassTemplateDecl>(TD))
1315  return TemplateNameKindForDiagnostics::ClassTemplate;
1316  if (isa<FunctionTemplateDecl>(TD))
1317  return TemplateNameKindForDiagnostics::FunctionTemplate;
1318  if (isa<VarTemplateDecl>(TD))
1319  return TemplateNameKindForDiagnostics::VarTemplate;
1320  if (isa<TypeAliasTemplateDecl>(TD))
1321  return TemplateNameKindForDiagnostics::AliasTemplate;
1322  if (isa<TemplateTemplateParmDecl>(TD))
1323  return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1324  if (isa<ConceptDecl>(TD))
1325  return TemplateNameKindForDiagnostics::Concept;
1326  return TemplateNameKindForDiagnostics::DependentTemplate;
1327 }
1328 
1330  assert(DC->getLexicalParent() == CurContext &&
1331  "The next DeclContext should be lexically contained in the current one.");
1332  CurContext = DC;
1333  S->setEntity(DC);
1334 }
1335 
1337  assert(CurContext && "DeclContext imbalance!");
1338 
1339  CurContext = CurContext->getLexicalParent();
1340  assert(CurContext && "Popped translation unit!");
1341 }
1342 
1344  Decl *D) {
1345  // Unlike PushDeclContext, the context to which we return is not necessarily
1346  // the containing DC of TD, because the new context will be some pre-existing
1347  // TagDecl definition instead of a fresh one.
1348  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1349  CurContext = cast<TagDecl>(D)->getDefinition();
1350  assert(CurContext && "skipping definition of undefined tag");
1351  // Start lookups from the parent of the current context; we don't want to look
1352  // into the pre-existing complete definition.
1353  S->setEntity(CurContext->getLookupParent());
1354  return Result;
1355 }
1356 
1358  CurContext = static_cast<decltype(CurContext)>(Context);
1359 }
1360 
1361 /// EnterDeclaratorContext - Used when we must lookup names in the context
1362 /// of a declarator's nested name specifier.
1363 ///
1365  // C++0x [basic.lookup.unqual]p13:
1366  // A name used in the definition of a static data member of class
1367  // X (after the qualified-id of the static member) is looked up as
1368  // if the name was used in a member function of X.
1369  // C++0x [basic.lookup.unqual]p14:
1370  // If a variable member of a namespace is defined outside of the
1371  // scope of its namespace then any name used in the definition of
1372  // the variable member (after the declarator-id) is looked up as
1373  // if the definition of the variable member occurred in its
1374  // namespace.
1375  // Both of these imply that we should push a scope whose context
1376  // is the semantic context of the declaration. We can't use
1377  // PushDeclContext here because that context is not necessarily
1378  // lexically contained in the current context. Fortunately,
1379  // the containing scope should have the appropriate information.
1380 
1381  assert(!S->getEntity() && "scope already has entity");
1382 
1383 #ifndef NDEBUG
1384  Scope *Ancestor = S->getParent();
1385  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1386  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1387 #endif
1388 
1389  CurContext = DC;
1390  S->setEntity(DC);
1391 
1392  if (S->getParent()->isTemplateParamScope()) {
1393  // Also set the corresponding entities for all immediately-enclosing
1394  // template parameter scopes.
1395  EnterTemplatedContext(S->getParent(), DC);
1396  }
1397 }
1398 
1400  assert(S->getEntity() == CurContext && "Context imbalance!");
1401 
1402  // Switch back to the lexical context. The safety of this is
1403  // enforced by an assert in EnterDeclaratorContext.
1404  Scope *Ancestor = S->getParent();
1405  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1406  CurContext = Ancestor->getEntity();
1407 
1408  // We don't need to do anything with the scope, which is going to
1409  // disappear.
1410 }
1411 
1413  assert(S->isTemplateParamScope() &&
1414  "expected to be initializing a template parameter scope");
1415 
1416  // C++20 [temp.local]p7:
1417  // In the definition of a member of a class template that appears outside
1418  // of the class template definition, the name of a member of the class
1419  // template hides the name of a template-parameter of any enclosing class
1420  // templates (but not a template-parameter of the member if the member is a
1421  // class or function template).
1422  // C++20 [temp.local]p9:
1423  // In the definition of a class template or in the definition of a member
1424  // of such a template that appears outside of the template definition, for
1425  // each non-dependent base class (13.8.2.1), if the name of the base class
1426  // or the name of a member of the base class is the same as the name of a
1427  // template-parameter, the base class name or member name hides the
1428  // template-parameter name (6.4.10).
1429  //
1430  // This means that a template parameter scope should be searched immediately
1431  // after searching the DeclContext for which it is a template parameter
1432  // scope. For example, for
1433  // template<typename T> template<typename U> template<typename V>
1434  // void N::A<T>::B<U>::f(...)
1435  // we search V then B<U> (and base classes) then U then A<T> (and base
1436  // classes) then T then N then ::.
1437  unsigned ScopeDepth = getTemplateDepth(S);
1438  for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1439  DeclContext *SearchDCAfterScope = DC;
1440  for (; DC; DC = DC->getLookupParent()) {
1441  if (const TemplateParameterList *TPL =
1442  cast<Decl>(DC)->getDescribedTemplateParams()) {
1443  unsigned DCDepth = TPL->getDepth() + 1;
1444  if (DCDepth > ScopeDepth)
1445  continue;
1446  if (ScopeDepth == DCDepth)
1447  SearchDCAfterScope = DC = DC->getLookupParent();
1448  break;
1449  }
1450  }
1451  S->setLookupEntity(SearchDCAfterScope);
1452  }
1453 }
1454 
1456  // We assume that the caller has already called
1457  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1458  FunctionDecl *FD = D->getAsFunction();
1459  if (!FD)
1460  return;
1461 
1462  // Same implementation as PushDeclContext, but enters the context
1463  // from the lexical parent, rather than the top-level class.
1464  assert(CurContext == FD->getLexicalParent() &&
1465  "The next DeclContext should be lexically contained in the current one.");
1466  CurContext = FD;
1467  S->setEntity(CurContext);
1468 
1469  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1470  ParmVarDecl *Param = FD->getParamDecl(P);
1471  // If the parameter has an identifier, then add it to the scope
1472  if (Param->getIdentifier()) {
1473  S->AddDecl(Param);
1474  IdResolver.AddDecl(Param);
1475  }
1476  }
1477 }
1478 
1480  // Same implementation as PopDeclContext, but returns to the lexical parent,
1481  // rather than the top-level class.
1482  assert(CurContext && "DeclContext imbalance!");
1483  CurContext = CurContext->getLexicalParent();
1484  assert(CurContext && "Popped translation unit!");
1485 }
1486 
1487 /// Determine whether overloading is allowed for a new function
1488 /// declaration considering prior declarations of the same name.
1489 ///
1490 /// This routine determines whether overloading is possible, not
1491 /// whether a new declaration actually overloads a previous one.
1492 /// It will return true in C++ (where overloads are alway permitted)
1493 /// or, as a C extension, when either the new declaration or a
1494 /// previous one is declared with the 'overloadable' attribute.
1496  ASTContext &Context,
1497  const FunctionDecl *New) {
1498  if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1499  return true;
1500 
1501  // Multiversion function declarations are not overloads in the
1502  // usual sense of that term, but lookup will report that an
1503  // overload set was found if more than one multiversion function
1504  // declaration is present for the same name. It is therefore
1505  // inadequate to assume that some prior declaration(s) had
1506  // the overloadable attribute; checking is required. Since one
1507  // declaration is permitted to omit the attribute, it is necessary
1508  // to check at least two; hence the 'any_of' check below. Note that
1509  // the overloadable attribute is implicitly added to declarations
1510  // that were required to have it but did not.
1511  if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1512  return llvm::any_of(Previous, [](const NamedDecl *ND) {
1513  return ND->hasAttr<OverloadableAttr>();
1514  });
1515  } else if (Previous.getResultKind() == LookupResult::Found)
1516  return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1517 
1518  return false;
1519 }
1520 
1521 /// Add this decl to the scope shadowed decl chains.
1522 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1523  // Move up the scope chain until we find the nearest enclosing
1524  // non-transparent context. The declaration will be introduced into this
1525  // scope.
1526  while (S->getEntity() && S->getEntity()->isTransparentContext())
1527  S = S->getParent();
1528 
1529  // Add scoped declarations into their context, so that they can be
1530  // found later. Declarations without a context won't be inserted
1531  // into any context.
1532  if (AddToContext)
1533  CurContext->addDecl(D);
1534 
1535  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1536  // are function-local declarations.
1537  if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1538  return;
1539 
1540  // Template instantiations should also not be pushed into scope.
1541  if (isa<FunctionDecl>(D) &&
1542  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1543  return;
1544 
1545  if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1546  S->AddDecl(D);
1547  return;
1548  }
1549  // If this replaces anything in the current scope,
1550  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1551  IEnd = IdResolver.end();
1552  for (; I != IEnd; ++I) {
1553  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1554  S->RemoveDecl(*I);
1555  IdResolver.RemoveDecl(*I);
1556 
1557  // Should only need to replace one decl.
1558  break;
1559  }
1560  }
1561 
1562  S->AddDecl(D);
1563 
1564  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1565  // Implicitly-generated labels may end up getting generated in an order that
1566  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1567  // the label at the appropriate place in the identifier chain.
1568  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1569  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1570  if (IDC == CurContext) {
1571  if (!S->isDeclScope(*I))
1572  continue;
1573  } else if (IDC->Encloses(CurContext))
1574  break;
1575  }
1576 
1577  IdResolver.InsertDeclAfter(I, D);
1578  } else {
1579  IdResolver.AddDecl(D);
1580  }
1581  warnOnReservedIdentifier(D);
1582 }
1583 
1585  bool AllowInlineNamespace) const {
1586  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1587 }
1588 
1590  DeclContext *TargetDC = DC->getPrimaryContext();
1591  do {
1592  if (DeclContext *ScopeDC = S->getEntity())
1593  if (ScopeDC->getPrimaryContext() == TargetDC)
1594  return S;
1595  } while ((S = S->getParent()));
1596 
1597  return nullptr;
1598 }
1599 
1601  DeclContext*,
1602  ASTContext&);
1603 
1604 /// Filters out lookup results that don't fall within the given scope
1605 /// as determined by isDeclInScope.
1607  bool ConsiderLinkage,
1608  bool AllowInlineNamespace) {
1610  while (F.hasNext()) {
1611  NamedDecl *D = F.next();
1612 
1613  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1614  continue;
1615 
1616  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1617  continue;
1618 
1619  F.erase();
1620  }
1621 
1622  F.done();
1623 }
1624 
1625 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1626 /// have compatible owning modules.
1628  // [module.interface]p7:
1629  // A declaration is attached to a module as follows:
1630  // - If the declaration is a non-dependent friend declaration that nominates a
1631  // function with a declarator-id that is a qualified-id or template-id or that
1632  // nominates a class other than with an elaborated-type-specifier with neither
1633  // a nested-name-specifier nor a simple-template-id, it is attached to the
1634  // module to which the friend is attached ([basic.link]).
1635  if (New->getFriendObjectKind() &&
1638  makeMergedDefinitionVisible(New);
1639  return false;
1640  }
1641 
1642  Module *NewM = New->getOwningModule();
1643  Module *OldM = Old->getOwningModule();
1644 
1645  if (NewM && NewM->isPrivateModule())
1646  NewM = NewM->Parent;
1647  if (OldM && OldM->isPrivateModule())
1648  OldM = OldM->Parent;
1649 
1650  if (NewM == OldM)
1651  return false;
1652 
1653  if (NewM && OldM) {
1654  // A module implementation unit has visibility of the decls in its
1655  // implicitly imported interface.
1656  if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1657  return false;
1658 
1659  // Partitions are part of the module, but a partition could import another
1660  // module, so verify that the PMIs agree.
1661  if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1664  return false;
1665  }
1666 
1667  bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1668  bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1669  if (NewIsModuleInterface || OldIsModuleInterface) {
1670  // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1671  // if a declaration of D [...] appears in the purview of a module, all
1672  // other such declarations shall appear in the purview of the same module
1673  Diag(New->getLocation(), diag::err_mismatched_owning_module)
1674  << New
1675  << NewIsModuleInterface
1676  << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1677  << OldIsModuleInterface
1678  << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1679  Diag(Old->getLocation(), diag::note_previous_declaration);
1680  New->setInvalidDecl();
1681  return true;
1682  }
1683 
1684  return false;
1685 }
1686 
1687 // [module.interface]p6:
1688 // A redeclaration of an entity X is implicitly exported if X was introduced by
1689 // an exported declaration; otherwise it shall not be exported.
1691  // [module.interface]p1:
1692  // An export-declaration shall inhabit a namespace scope.
1693  //
1694  // So it is meaningless to talk about redeclaration which is not at namespace
1695  // scope.
1696  if (!New->getLexicalDeclContext()
1698  ->isFileContext() ||
1699  !Old->getLexicalDeclContext()
1701  ->isFileContext())
1702  return false;
1703 
1704  bool IsNewExported = New->isInExportDeclContext();
1705  bool IsOldExported = Old->isInExportDeclContext();
1706 
1707  // It should be irrevelant if both of them are not exported.
1708  if (!IsNewExported && !IsOldExported)
1709  return false;
1710 
1711  if (IsOldExported)
1712  return false;
1713 
1714  assert(IsNewExported);
1715 
1716  auto Lk = Old->getFormalLinkage();
1717  int S = 0;
1718  if (Lk == Linkage::Internal)
1719  S = 1;
1720  else if (Lk == Linkage::Module)
1721  S = 2;
1722  Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1723  Diag(Old->getLocation(), diag::note_previous_declaration);
1724  return true;
1725 }
1726 
1727 // A wrapper function for checking the semantic restrictions of
1728 // a redeclaration within a module.
1730  if (CheckRedeclarationModuleOwnership(New, Old))
1731  return true;
1732 
1733  if (CheckRedeclarationExported(New, Old))
1734  return true;
1735 
1736  return false;
1737 }
1738 
1739 // Check the redefinition in C++20 Modules.
1740 //
1741 // [basic.def.odr]p14:
1742 // For any definable item D with definitions in multiple translation units,
1743 // - if D is a non-inline non-templated function or variable, or
1744 // - if the definitions in different translation units do not satisfy the
1745 // following requirements,
1746 // the program is ill-formed; a diagnostic is required only if the definable
1747 // item is attached to a named module and a prior definition is reachable at
1748 // the point where a later definition occurs.
1749 // - Each such definition shall not be attached to a named module
1750 // ([module.unit]).
1751 // - Each such definition shall consist of the same sequence of tokens, ...
1752 // ...
1753 //
1754 // Return true if the redefinition is not allowed. Return false otherwise.
1756  const NamedDecl *Old) const {
1757  assert(getASTContext().isSameEntity(New, Old) &&
1758  "New and Old are not the same definition, we should diagnostic it "
1759  "immediately instead of checking it.");
1760  assert(const_cast<Sema *>(this)->isReachable(New) &&
1761  const_cast<Sema *>(this)->isReachable(Old) &&
1762  "We shouldn't see unreachable definitions here.");
1763 
1764  Module *NewM = New->getOwningModule();
1765  Module *OldM = Old->getOwningModule();
1766 
1767  // We only checks for named modules here. The header like modules is skipped.
1768  // FIXME: This is not right if we import the header like modules in the module
1769  // purview.
1770  //
1771  // For example, assuming "header.h" provides definition for `D`.
1772  // ```C++
1773  // //--- M.cppm
1774  // export module M;
1775  // import "header.h"; // or #include "header.h" but import it by clang modules
1776  // actually.
1777  //
1778  // //--- Use.cpp
1779  // import M;
1780  // import "header.h"; // or uses clang modules.
1781  // ```
1782  //
1783  // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1784  // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1785  // reject it. But the current implementation couldn't detect the case since we
1786  // don't record the information about the importee modules.
1787  //
1788  // But this might not be painful in practice. Since the design of C++20 Named
1789  // Modules suggests us to use headers in global module fragment instead of
1790  // module purview.
1791  if (NewM && NewM->isHeaderLikeModule())
1792  NewM = nullptr;
1793  if (OldM && OldM->isHeaderLikeModule())
1794  OldM = nullptr;
1795 
1796  if (!NewM && !OldM)
1797  return true;
1798 
1799  // [basic.def.odr]p14.3
1800  // Each such definition shall not be attached to a named module
1801  // ([module.unit]).
1802  if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1803  return true;
1804 
1805  // Then New and Old lives in the same TU if their share one same module unit.
1806  if (NewM)
1807  NewM = NewM->getTopLevelModule();
1808  if (OldM)
1809  OldM = OldM->getTopLevelModule();
1810  return OldM == NewM;
1811 }
1812 
1814  if (D->getDeclContext()->isFileContext())
1815  return false;
1816 
1817  return isa<UsingShadowDecl>(D) ||
1818  isa<UnresolvedUsingTypenameDecl>(D) ||
1819  isa<UnresolvedUsingValueDecl>(D);
1820 }
1821 
1822 /// Removes using shadow declarations not at class scope from the lookup
1823 /// results.
1826  while (F.hasNext())
1828  F.erase();
1829 
1830  F.done();
1831 }
1832 
1833 /// Check for this common pattern:
1834 /// @code
1835 /// class S {
1836 /// S(const S&); // DO NOT IMPLEMENT
1837 /// void operator=(const S&); // DO NOT IMPLEMENT
1838 /// };
1839 /// @endcode
1841  // FIXME: Should check for private access too but access is set after we get
1842  // the decl here.
1844  return false;
1845 
1846  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1847  return CD->isCopyConstructor();
1848  return D->isCopyAssignmentOperator();
1849 }
1850 
1851 // We need this to handle
1852 //
1853 // typedef struct {
1854 // void *foo() { return 0; }
1855 // } A;
1856 //
1857 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1858 // for example. If 'A', foo will have external linkage. If we have '*A',
1859 // foo will have no linkage. Since we can't know until we get to the end
1860 // of the typedef, this function finds out if D might have non-external linkage.
1861 // Callers should verify at the end of the TU if it D has external linkage or
1862 // not.
1863 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1864  const DeclContext *DC = D->getDeclContext();
1865  while (!DC->isTranslationUnit()) {
1866  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1867  if (!RD->hasNameForLinkage())
1868  return true;
1869  }
1870  DC = DC->getParent();
1871  }
1872 
1873  return !D->isExternallyVisible();
1874 }
1875 
1876 // FIXME: This needs to be refactored; some other isInMainFile users want
1877 // these semantics.
1878 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1879  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1880  return false;
1881  return S.SourceMgr.isInMainFile(Loc);
1882 }
1883 
1885  assert(D);
1886 
1887  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1888  return false;
1889 
1890  // Ignore all entities declared within templates, and out-of-line definitions
1891  // of members of class templates.
1892  if (D->getDeclContext()->isDependentContext() ||
1894  return false;
1895 
1896  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1897  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1898  return false;
1899  // A non-out-of-line declaration of a member specialization was implicitly
1900  // instantiated; it's the out-of-line declaration that we're interested in.
1901  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1902  FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1903  return false;
1904 
1905  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1906  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1907  return false;
1908  } else {
1909  // 'static inline' functions are defined in headers; don't warn.
1910  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1911  return false;
1912  }
1913 
1914  if (FD->doesThisDeclarationHaveABody() &&
1915  Context.DeclMustBeEmitted(FD))
1916  return false;
1917  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1918  // Constants and utility variables are defined in headers with internal
1919  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1920  // like "inline".)
1921  if (!isMainFileLoc(*this, VD->getLocation()))
1922  return false;
1923 
1924  if (Context.DeclMustBeEmitted(VD))
1925  return false;
1926 
1927  if (VD->isStaticDataMember() &&
1928  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1929  return false;
1930  if (VD->isStaticDataMember() &&
1931  VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1932  VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1933  return false;
1934 
1935  if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1936  return false;
1937  } else {
1938  return false;
1939  }
1940 
1941  // Only warn for unused decls internal to the translation unit.
1942  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1943  // for inline functions defined in the main source file, for instance.
1944  return mightHaveNonExternalLinkage(D);
1945 }
1946 
1948  if (!D)
1949  return;
1950 
1951  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1952  const FunctionDecl *First = FD->getFirstDecl();
1953  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1954  return; // First should already be in the vector.
1955  }
1956 
1957  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1958  const VarDecl *First = VD->getFirstDecl();
1959  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1960  return; // First should already be in the vector.
1961  }
1962 
1963  if (ShouldWarnIfUnusedFileScopedDecl(D))
1964  UnusedFileScopedDecls.push_back(D);
1965 }
1966 
1967 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1968  const NamedDecl *D) {
1969  if (D->isInvalidDecl())
1970  return false;
1971 
1972  if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1973  // For a decomposition declaration, warn if none of the bindings are
1974  // referenced, instead of if the variable itself is referenced (which
1975  // it is, by the bindings' expressions).
1976  bool IsAllPlaceholders = true;
1977  for (const auto *BD : DD->bindings()) {
1978  if (BD->isReferenced())
1979  return false;
1980  IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1981  }
1982  if (IsAllPlaceholders)
1983  return false;
1984  } else if (!D->getDeclName()) {
1985  return false;
1986  } else if (D->isReferenced() || D->isUsed()) {
1987  return false;
1988  }
1989 
1990  if (D->isPlaceholderVar(LangOpts))
1991  return false;
1992 
1993  if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1994  D->hasAttr<CleanupAttr>())
1995  return false;
1996 
1997  if (isa<LabelDecl>(D))
1998  return true;
1999 
2000  // Except for labels, we only care about unused decls that are local to
2001  // functions.
2002  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2003  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2004  // For dependent types, the diagnostic is deferred.
2005  WithinFunction =
2006  WithinFunction || (R->isLocalClass() && !R->isDependentType());
2007  if (!WithinFunction)
2008  return false;
2009 
2010  if (isa<TypedefNameDecl>(D))
2011  return true;
2012 
2013  // White-list anything that isn't a local variable.
2014  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2015  return false;
2016 
2017  // Types of valid local variables should be complete, so this should succeed.
2018  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2019 
2020  const Expr *Init = VD->getInit();
2021  if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2022  Init = Cleanups->getSubExpr();
2023 
2024  const auto *Ty = VD->getType().getTypePtr();
2025 
2026  // Only look at the outermost level of typedef.
2027  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2028  // Allow anything marked with __attribute__((unused)).
2029  if (TT->getDecl()->hasAttr<UnusedAttr>())
2030  return false;
2031  }
2032 
2033  // Warn for reference variables whose initializtion performs lifetime
2034  // extension.
2035  if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2036  MTE && MTE->getExtendingDecl()) {
2037  Ty = VD->getType().getNonReferenceType().getTypePtr();
2038  Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2039  }
2040 
2041  // If we failed to complete the type for some reason, or if the type is
2042  // dependent, don't diagnose the variable.
2043  if (Ty->isIncompleteType() || Ty->isDependentType())
2044  return false;
2045 
2046  // Look at the element type to ensure that the warning behaviour is
2047  // consistent for both scalars and arrays.
2048  Ty = Ty->getBaseElementTypeUnsafe();
2049 
2050  if (const TagType *TT = Ty->getAs<TagType>()) {
2051  const TagDecl *Tag = TT->getDecl();
2052  if (Tag->hasAttr<UnusedAttr>())
2053  return false;
2054 
2055  if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2056  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2057  return false;
2058 
2059  if (Init) {
2060  const auto *Construct =
2061  dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2062  if (Construct && !Construct->isElidable()) {
2063  const CXXConstructorDecl *CD = Construct->getConstructor();
2064  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2065  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2066  return false;
2067  }
2068 
2069  // Suppress the warning if we don't know how this is constructed, and
2070  // it could possibly be non-trivial constructor.
2071  if (Init->isTypeDependent()) {
2072  for (const CXXConstructorDecl *Ctor : RD->ctors())
2073  if (!Ctor->isTrivial())
2074  return false;
2075  }
2076 
2077  // Suppress the warning if the constructor is unresolved because
2078  // its arguments are dependent.
2079  if (isa<CXXUnresolvedConstructExpr>(Init))
2080  return false;
2081  }
2082  }
2083  }
2084 
2085  // TODO: __attribute__((unused)) templates?
2086  }
2087 
2088  return true;
2089 }
2090 
2091 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2092  FixItHint &Hint) {
2093  if (isa<LabelDecl>(D)) {
2095  D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2096  /*SkipTrailingWhitespaceAndNewline=*/false);
2097  if (AfterColon.isInvalid())
2098  return;
2099  Hint = FixItHint::CreateRemoval(
2100  CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2101  }
2102 }
2103 
2105  DiagnoseUnusedNestedTypedefs(
2106  D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2107 }
2108 
2110  DiagReceiverTy DiagReceiver) {
2111  if (D->getTypeForDecl()->isDependentType())
2112  return;
2113 
2114  for (auto *TmpD : D->decls()) {
2115  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2116  DiagnoseUnusedDecl(T, DiagReceiver);
2117  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2118  DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2119  }
2120 }
2121 
2123  DiagnoseUnusedDecl(
2124  D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2125 }
2126 
2127 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2128 /// unless they are marked attr(unused).
2129 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2130  if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2131  return;
2132 
2133  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2134  // typedefs can be referenced later on, so the diagnostics are emitted
2135  // at end-of-translation-unit.
2136  UnusedLocalTypedefNameCandidates.insert(TD);
2137  return;
2138  }
2139 
2140  FixItHint Hint;
2141  GenerateFixForUnusedDecl(D, Context, Hint);
2142 
2143  unsigned DiagID;
2144  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2145  DiagID = diag::warn_unused_exception_param;
2146  else if (isa<LabelDecl>(D))
2147  DiagID = diag::warn_unused_label;
2148  else
2149  DiagID = diag::warn_unused_variable;
2150 
2151  SourceLocation DiagLoc = D->getLocation();
2152  DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2153 }
2154 
2156  DiagReceiverTy DiagReceiver) {
2157  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2158  // it's not really unused.
2159  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2160  return;
2161 
2162  // In C++, `_` variables behave as if they were maybe_unused
2163  if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2164  return;
2165 
2166  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2167 
2168  if (Ty->isReferenceType() || Ty->isDependentType())
2169  return;
2170 
2171  if (const TagType *TT = Ty->getAs<TagType>()) {
2172  const TagDecl *Tag = TT->getDecl();
2173  if (Tag->hasAttr<UnusedAttr>())
2174  return;
2175  // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2176  // mimic gcc's behavior.
2177  if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2178  RD && !RD->hasAttr<WarnUnusedAttr>())
2179  return;
2180  }
2181 
2182  // Don't warn about __block Objective-C pointer variables, as they might
2183  // be assigned in the block but not used elsewhere for the purpose of lifetime
2184  // extension.
2185  if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2186  return;
2187 
2188  // Don't warn about Objective-C pointer variables with precise lifetime
2189  // semantics; they can be used to ensure ARC releases the object at a known
2190  // time, which may mean assignment but no other references.
2191  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2192  return;
2193 
2194  auto iter = RefsMinusAssignments.find(VD);
2195  if (iter == RefsMinusAssignments.end())
2196  return;
2197 
2198  assert(iter->getSecond() >= 0 &&
2199  "Found a negative number of references to a VarDecl");
2200  if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2201  // Assume the given VarDecl is "used" if its ref count stored in
2202  // `RefMinusAssignments` is positive, with one exception.
2203  //
2204  // For a C++ variable whose decl (with initializer) entirely consist the
2205  // condition expression of a if/while/for construct,
2206  // Clang creates a DeclRefExpr for the condition expression rather than a
2207  // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2208  // count stored in `RefMinusAssignment` equals 1 when the variable is never
2209  // used in the body of the if/while/for construct.
2210  bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2211  if (!UnusedCXXCondDecl)
2212  return;
2213  }
2214 
2215  unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2216  : diag::warn_unused_but_set_variable;
2217  DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2218 }
2219 
2220 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2221  Sema::DiagReceiverTy DiagReceiver) {
2222  // Verify that we have no forward references left. If so, there was a goto
2223  // or address of a label taken, but no definition of it. Label fwd
2224  // definitions are indicated with a null substmt which is also not a resolved
2225  // MS inline assembly label name.
2226  bool Diagnose = false;
2227  if (L->isMSAsmLabel())
2228  Diagnose = !L->isResolvedMSAsmLabel();
2229  else
2230  Diagnose = L->getStmt() == nullptr;
2231  if (Diagnose)
2232  DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2233  << L);
2234 }
2235 
2237  S->applyNRVO();
2238 
2239  if (S->decl_empty()) return;
2240  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2241  "Scope shouldn't contain decls!");
2242 
2243  /// We visit the decls in non-deterministic order, but we want diagnostics
2244  /// emitted in deterministic order. Collect any diagnostic that may be emitted
2245  /// and sort the diagnostics before emitting them, after we visited all decls.
2246  struct LocAndDiag {
2247  SourceLocation Loc;
2248  std::optional<SourceLocation> PreviousDeclLoc;
2249  PartialDiagnostic PD;
2250  };
2251  SmallVector<LocAndDiag, 16> DeclDiags;
2252  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2253  DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2254  };
2255  auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2256  SourceLocation PreviousDeclLoc,
2257  PartialDiagnostic PD) {
2258  DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2259  };
2260 
2261  for (auto *TmpD : S->decls()) {
2262  assert(TmpD && "This decl didn't get pushed??");
2263 
2264  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2265  NamedDecl *D = cast<NamedDecl>(TmpD);
2266 
2267  // Diagnose unused variables in this scope.
2268  if (!S->hasUnrecoverableErrorOccurred()) {
2269  DiagnoseUnusedDecl(D, addDiag);
2270  if (const auto *RD = dyn_cast<RecordDecl>(D))
2271  DiagnoseUnusedNestedTypedefs(RD, addDiag);
2272  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2273  DiagnoseUnusedButSetDecl(VD, addDiag);
2274  RefsMinusAssignments.erase(VD);
2275  }
2276  }
2277 
2278  if (!D->getDeclName()) continue;
2279 
2280  // If this was a forward reference to a label, verify it was defined.
2281  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2282  CheckPoppedLabel(LD, *this, addDiag);
2283 
2284  // Remove this name from our lexical scope, and warn on it if we haven't
2285  // already.
2286  IdResolver.RemoveDecl(D);
2287  auto ShadowI = ShadowingDecls.find(D);
2288  if (ShadowI != ShadowingDecls.end()) {
2289  if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2290  addDiagWithPrev(D->getLocation(), FD->getLocation(),
2291  PDiag(diag::warn_ctor_parm_shadows_field)
2292  << D << FD << FD->getParent());
2293  }
2294  ShadowingDecls.erase(ShadowI);
2295  }
2296  }
2297 
2298  llvm::sort(DeclDiags,
2299  [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2300  // The particular order for diagnostics is not important, as long
2301  // as the order is deterministic. Using the raw location is going
2302  // to generally be in source order unless there are macro
2303  // expansions involved.
2304  return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2305  });
2306  for (const LocAndDiag &D : DeclDiags) {
2307  Diag(D.Loc, D.PD);
2308  if (D.PreviousDeclLoc)
2309  Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2310  }
2311 }
2312 
2313 /// Look for an Objective-C class in the translation unit.
2314 ///
2315 /// \param Id The name of the Objective-C class we're looking for. If
2316 /// typo-correction fixes this name, the Id will be updated
2317 /// to the fixed name.
2318 ///
2319 /// \param IdLoc The location of the name in the translation unit.
2320 ///
2321 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2322 /// if there is no class with the given name.
2323 ///
2324 /// \returns The declaration of the named Objective-C class, or NULL if the
2325 /// class could not be found.
2327  SourceLocation IdLoc,
2328  bool DoTypoCorrection) {
2329  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2330  // creation from this context.
2331  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2332 
2333  if (!IDecl && DoTypoCorrection) {
2334  // Perform typo correction at the given location, but only if we
2335  // find an Objective-C class name.
2337  if (TypoCorrection C =
2338  CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2339  TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2340  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2341  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2342  Id = IDecl->getIdentifier();
2343  }
2344  }
2345  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2346  // This routine must always return a class definition, if any.
2347  if (Def && Def->getDefinition())
2348  Def = Def->getDefinition();
2349  return Def;
2350 }
2351 
2352 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2353 /// from S, where a non-field would be declared. This routine copes
2354 /// with the difference between C and C++ scoping rules in structs and
2355 /// unions. For example, the following code is well-formed in C but
2356 /// ill-formed in C++:
2357 /// @code
2358 /// struct S6 {
2359 /// enum { BAR } e;
2360 /// };
2361 ///
2362 /// void test_S6() {
2363 /// struct S6 a;
2364 /// a.e = BAR;
2365 /// }
2366 /// @endcode
2367 /// For the declaration of BAR, this routine will return a different
2368 /// scope. The scope S will be the scope of the unnamed enumeration
2369 /// within S6. In C++, this routine will return the scope associated
2370 /// with S6, because the enumeration's scope is a transparent
2371 /// context but structures can contain non-field names. In C, this
2372 /// routine will return the translation unit scope, since the
2373 /// enumeration's scope is a transparent context and structures cannot
2374 /// contain non-field names.
2376  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2377  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2378  (S->isClassScope() && !getLangOpts().CPlusPlus))
2379  S = S->getParent();
2380  return S;
2381 }
2382 
2383 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2385  switch (Error) {
2386  case ASTContext::GE_None:
2387  return "";
2389  return BuiltinInfo.getHeaderName(ID);
2391  return "stdio.h";
2393  return "setjmp.h";
2395  return "ucontext.h";
2396  }
2397  llvm_unreachable("unhandled error kind");
2398 }
2399 
2401  unsigned ID, SourceLocation Loc) {
2403 
2404  if (getLangOpts().CPlusPlus) {
2405  LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2406  Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2407  CLinkageDecl->setImplicit();
2408  Parent->addDecl(CLinkageDecl);
2409  Parent = CLinkageDecl;
2410  }
2411 
2412  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2413  /*TInfo=*/nullptr, SC_Extern,
2414  getCurFPFeatures().isFPConstrained(),
2415  false, Type->isFunctionProtoType());
2416  New->setImplicit();
2417  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2418 
2419  // Create Decl objects for each parameter, adding them to the
2420  // FunctionDecl.
2421  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2423  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2425  Context, New, SourceLocation(), SourceLocation(), nullptr,
2426  FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2427  parm->setScopeInfo(0, i);
2428  Params.push_back(parm);
2429  }
2430  New->setParams(Params);
2431  }
2432 
2433  AddKnownFunctionAttributes(New);
2434  return New;
2435 }
2436 
2437 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2438 /// file scope. lazily create a decl for it. ForRedeclaration is true
2439 /// if we're creating this built-in in anticipation of redeclaring the
2440 /// built-in.
2442  Scope *S, bool ForRedeclaration,
2443  SourceLocation Loc) {
2444  LookupNecessaryTypesForBuiltin(S, ID);
2445 
2447  QualType R = Context.GetBuiltinType(ID, Error);
2448  if (Error) {
2449  if (!ForRedeclaration)
2450  return nullptr;
2451 
2452  // If we have a builtin without an associated type we should not emit a
2453  // warning when we were not able to find a type for it.
2454  if (Error == ASTContext::GE_Missing_type ||
2455  Context.BuiltinInfo.allowTypeMismatch(ID))
2456  return nullptr;
2457 
2458  // If we could not find a type for setjmp it is because the jmp_buf type was
2459  // not defined prior to the setjmp declaration.
2460  if (Error == ASTContext::GE_Missing_setjmp) {
2461  Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2462  << Context.BuiltinInfo.getName(ID);
2463  return nullptr;
2464  }
2465 
2466  // Generally, we emit a warning that the declaration requires the
2467  // appropriate header.
2468  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2469  << getHeaderName(Context.BuiltinInfo, ID, Error)
2470  << Context.BuiltinInfo.getName(ID);
2471  return nullptr;
2472  }
2473 
2474  if (!ForRedeclaration &&
2477  Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2478  : diag::ext_implicit_lib_function_decl)
2479  << Context.BuiltinInfo.getName(ID) << R;
2480  if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2481  Diag(Loc, diag::note_include_header_or_declare)
2482  << Header << Context.BuiltinInfo.getName(ID);
2483  }
2484 
2485  if (R.isNull())
2486  return nullptr;
2487 
2488  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2489  RegisterLocallyScopedExternCDecl(New, S);
2490 
2491  // TUScope is the translation-unit scope to insert this function into.
2492  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2493  // relate Scopes to DeclContexts, and probably eliminate CurContext
2494  // entirely, but we're not there yet.
2495  DeclContext *SavedContext = CurContext;
2496  CurContext = New->getDeclContext();
2497  PushOnScopeChains(New, TUScope);
2498  CurContext = SavedContext;
2499  return New;
2500 }
2501 
2502 /// Typedef declarations don't have linkage, but they still denote the same
2503 /// entity if their types are the same.
2504 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2505 /// isSameEntity.
2509  // This is only interesting when modules are enabled.
2510  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2511  return;
2512 
2513  // Empty sets are uninteresting.
2514  if (Previous.empty())
2515  return;
2516 
2517  LookupResult::Filter Filter = Previous.makeFilter();
2518  while (Filter.hasNext()) {
2519  NamedDecl *Old = Filter.next();
2520 
2521  // Non-hidden declarations are never ignored.
2522  if (S.isVisible(Old))
2523  continue;
2524 
2525  // Declarations of the same entity are not ignored, even if they have
2526  // different linkages.
2527  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2528  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2529  Decl->getUnderlyingType()))
2530  continue;
2531 
2532  // If both declarations give a tag declaration a typedef name for linkage
2533  // purposes, then they declare the same entity.
2534  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2535  Decl->getAnonDeclWithTypedefName())
2536  continue;
2537  }
2538 
2539  Filter.erase();
2540  }
2541 
2542  Filter.done();
2543 }
2544 
2546  QualType OldType;
2547  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2548  OldType = OldTypedef->getUnderlyingType();
2549  else
2550  OldType = Context.getTypeDeclType(Old);
2551  QualType NewType = New->getUnderlyingType();
2552 
2553  if (NewType->isVariablyModifiedType()) {
2554  // Must not redefine a typedef with a variably-modified type.
2555  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2556  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2557  << Kind << NewType;
2558  if (Old->getLocation().isValid())
2559  notePreviousDefinition(Old, New->getLocation());
2560  New->setInvalidDecl();
2561  return true;
2562  }
2563 
2564  if (OldType != NewType &&
2565  !OldType->isDependentType() &&
2566  !NewType->isDependentType() &&
2567  !Context.hasSameType(OldType, NewType)) {
2568  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2569  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2570  << Kind << NewType << OldType;
2571  if (Old->getLocation().isValid())
2572  notePreviousDefinition(Old, New->getLocation());
2573  New->setInvalidDecl();
2574  return true;
2575  }
2576  return false;
2577 }
2578 
2579 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2580 /// same name and scope as a previous declaration 'Old'. Figure out
2581 /// how to resolve this situation, merging decls or emitting
2582 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2583 ///
2585  LookupResult &OldDecls) {
2586  // If the new decl is known invalid already, don't bother doing any
2587  // merging checks.
2588  if (New->isInvalidDecl()) return;
2589 
2590  // Allow multiple definitions for ObjC built-in typedefs.
2591  // FIXME: Verify the underlying types are equivalent!
2592  if (getLangOpts().ObjC) {
2593  const IdentifierInfo *TypeID = New->getIdentifier();
2594  switch (TypeID->getLength()) {
2595  default: break;
2596  case 2:
2597  {
2598  if (!TypeID->isStr("id"))
2599  break;
2600  QualType T = New->getUnderlyingType();
2601  if (!T->isPointerType())
2602  break;
2603  if (!T->isVoidPointerType()) {
2604  QualType PT = T->castAs<PointerType>()->getPointeeType();
2605  if (!PT->isStructureType())
2606  break;
2607  }
2608  Context.setObjCIdRedefinitionType(T);
2609  // Install the built-in type for 'id', ignoring the current definition.
2610  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2611  return;
2612  }
2613  case 5:
2614  if (!TypeID->isStr("Class"))
2615  break;
2617  // Install the built-in type for 'Class', ignoring the current definition.
2618  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2619  return;
2620  case 3:
2621  if (!TypeID->isStr("SEL"))
2622  break;
2624  // Install the built-in type for 'SEL', ignoring the current definition.
2625  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2626  return;
2627  }
2628  // Fall through - the typedef name was not a builtin type.
2629  }
2630 
2631  // Verify the old decl was also a type.
2632  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2633  if (!Old) {
2634  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2635  << New->getDeclName();
2636 
2637  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2638  if (OldD->getLocation().isValid())
2639  notePreviousDefinition(OldD, New->getLocation());
2640 
2641  return New->setInvalidDecl();
2642  }
2643 
2644  // If the old declaration is invalid, just give up here.
2645  if (Old->isInvalidDecl())
2646  return New->setInvalidDecl();
2647 
2648  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2649  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2650  auto *NewTag = New->getAnonDeclWithTypedefName();
2651  NamedDecl *Hidden = nullptr;
2652  if (OldTag && NewTag &&
2653  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2654  !hasVisibleDefinition(OldTag, &Hidden)) {
2655  // There is a definition of this tag, but it is not visible. Use it
2656  // instead of our tag.
2657  New->setTypeForDecl(OldTD->getTypeForDecl());
2658  if (OldTD->isModed())
2659  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2660  OldTD->getUnderlyingType());
2661  else
2662  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2663 
2664  // Make the old tag definition visible.
2665  makeMergedDefinitionVisible(Hidden);
2666 
2667  // If this was an unscoped enumeration, yank all of its enumerators
2668  // out of the scope.
2669  if (isa<EnumDecl>(NewTag)) {
2670  Scope *EnumScope = getNonFieldDeclScope(S);
2671  for (auto *D : NewTag->decls()) {
2672  auto *ED = cast<EnumConstantDecl>(D);
2673  assert(EnumScope->isDeclScope(ED));
2674  EnumScope->RemoveDecl(ED);
2675  IdResolver.RemoveDecl(ED);
2676  ED->getLexicalDeclContext()->removeDecl(ED);
2677  }
2678  }
2679  }
2680  }
2681 
2682  // If the typedef types are not identical, reject them in all languages and
2683  // with any extensions enabled.
2684  if (isIncompatibleTypedef(Old, New))
2685  return;
2686 
2687  // The types match. Link up the redeclaration chain and merge attributes if
2688  // the old declaration was a typedef.
2689  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2690  New->setPreviousDecl(Typedef);
2691  mergeDeclAttributes(New, Old);
2692  }
2693 
2694  if (getLangOpts().MicrosoftExt)
2695  return;
2696 
2697  if (getLangOpts().CPlusPlus) {
2698  // C++ [dcl.typedef]p2:
2699  // In a given non-class scope, a typedef specifier can be used to
2700  // redefine the name of any type declared in that scope to refer
2701  // to the type to which it already refers.
2702  if (!isa<CXXRecordDecl>(CurContext))
2703  return;
2704 
2705  // C++0x [dcl.typedef]p4:
2706  // In a given class scope, a typedef specifier can be used to redefine
2707  // any class-name declared in that scope that is not also a typedef-name
2708  // to refer to the type to which it already refers.
2709  //
2710  // This wording came in via DR424, which was a correction to the
2711  // wording in DR56, which accidentally banned code like:
2712  //
2713  // struct S {
2714  // typedef struct A { } A;
2715  // };
2716  //
2717  // in the C++03 standard. We implement the C++0x semantics, which
2718  // allow the above but disallow
2719  //
2720  // struct S {
2721  // typedef int I;
2722  // typedef int I;
2723  // };
2724  //
2725  // since that was the intent of DR56.
2726  if (!isa<TypedefNameDecl>(Old))
2727  return;
2728 
2729  Diag(New->getLocation(), diag::err_redefinition)
2730  << New->getDeclName();
2731  notePreviousDefinition(Old, New->getLocation());
2732  return New->setInvalidDecl();
2733  }
2734 
2735  // Modules always permit redefinition of typedefs, as does C11.
2736  if (getLangOpts().Modules || getLangOpts().C11)
2737  return;
2738 
2739  // If we have a redefinition of a typedef in C, emit a warning. This warning
2740  // is normally mapped to an error, but can be controlled with
2741  // -Wtypedef-redefinition. If either the original or the redefinition is
2742  // in a system header, don't emit this for compatibility with GCC.
2743  if (getDiagnostics().getSuppressSystemWarnings() &&
2744  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2745  (Old->isImplicit() ||
2746  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2747  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2748  return;
2749 
2750  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2751  << New->getDeclName();
2752  notePreviousDefinition(Old, New->getLocation());
2753 }
2754 
2755 /// DeclhasAttr - returns true if decl Declaration already has the target
2756 /// attribute.
2757 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2758  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2759  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2760  for (const auto *i : D->attrs())
2761  if (i->getKind() == A->getKind()) {
2762  if (Ann) {
2763  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2764  return true;
2765  continue;
2766  }
2767  // FIXME: Don't hardcode this check
2768  if (OA && isa<OwnershipAttr>(i))
2769  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2770  return true;
2771  }
2772 
2773  return false;
2774 }
2775 
2777  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2778  return VD->isThisDeclarationADefinition();
2779  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2780  return TD->isCompleteDefinition() || TD->isBeingDefined();
2781  return true;
2782 }
2783 
2784 /// Merge alignment attributes from \p Old to \p New, taking into account the
2785 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2786 ///
2787 /// \return \c true if any attributes were added to \p New.
2788 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2789  // Look for alignas attributes on Old, and pick out whichever attribute
2790  // specifies the strictest alignment requirement.
2791  AlignedAttr *OldAlignasAttr = nullptr;
2792  AlignedAttr *OldStrictestAlignAttr = nullptr;
2793  unsigned OldAlign = 0;
2794  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2795  // FIXME: We have no way of representing inherited dependent alignments
2796  // in a case like:
2797  // template<int A, int B> struct alignas(A) X;
2798  // template<int A, int B> struct alignas(B) X {};
2799  // For now, we just ignore any alignas attributes which are not on the
2800  // definition in such a case.
2801  if (I->isAlignmentDependent())
2802  return false;
2803 
2804  if (I->isAlignas())
2805  OldAlignasAttr = I;
2806 
2807  unsigned Align = I->getAlignment(S.Context);
2808  if (Align > OldAlign) {
2809  OldAlign = Align;
2810  OldStrictestAlignAttr = I;
2811  }
2812  }
2813 
2814  // Look for alignas attributes on New.
2815  AlignedAttr *NewAlignasAttr = nullptr;
2816  unsigned NewAlign = 0;
2817  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2818  if (I->isAlignmentDependent())
2819  return false;
2820 
2821  if (I->isAlignas())
2822  NewAlignasAttr = I;
2823 
2824  unsigned Align = I->getAlignment(S.Context);
2825  if (Align > NewAlign)
2826  NewAlign = Align;
2827  }
2828 
2829  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2830  // Both declarations have 'alignas' attributes. We require them to match.
2831  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2832  // fall short. (If two declarations both have alignas, they must both match
2833  // every definition, and so must match each other if there is a definition.)
2834 
2835  // If either declaration only contains 'alignas(0)' specifiers, then it
2836  // specifies the natural alignment for the type.
2837  if (OldAlign == 0 || NewAlign == 0) {
2838  QualType Ty;
2839  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2840  Ty = VD->getType();
2841  else
2842  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2843 
2844  if (OldAlign == 0)
2845  OldAlign = S.Context.getTypeAlign(Ty);
2846  if (NewAlign == 0)
2847  NewAlign = S.Context.getTypeAlign(Ty);
2848  }
2849 
2850  if (OldAlign != NewAlign) {
2851  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2853  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2854  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2855  }
2856  }
2857 
2858  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2859  // C++11 [dcl.align]p6:
2860  // if any declaration of an entity has an alignment-specifier,
2861  // every defining declaration of that entity shall specify an
2862  // equivalent alignment.
2863  // C11 6.7.5/7:
2864  // If the definition of an object does not have an alignment
2865  // specifier, any other declaration of that object shall also
2866  // have no alignment specifier.
2867  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2868  << OldAlignasAttr;
2869  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2870  << OldAlignasAttr;
2871  }
2872 
2873  bool AnyAdded = false;
2874 
2875  // Ensure we have an attribute representing the strictest alignment.
2876  if (OldAlign > NewAlign) {
2877  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2878  Clone->setInherited(true);
2879  New->addAttr(Clone);
2880  AnyAdded = true;
2881  }
2882 
2883  // Ensure we have an alignas attribute if the old declaration had one.
2884  if (OldAlignasAttr && !NewAlignasAttr &&
2885  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2886  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2887  Clone->setInherited(true);
2888  New->addAttr(Clone);
2889  AnyAdded = true;
2890  }
2891 
2892  return AnyAdded;
2893 }
2894 
2895 #define WANT_DECL_MERGE_LOGIC
2896 #include "clang/Sema/AttrParsedAttrImpl.inc"
2897 #undef WANT_DECL_MERGE_LOGIC
2898 
2899 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2900  const InheritableAttr *Attr,
2902  // Diagnose any mutual exclusions between the attribute that we want to add
2903  // and attributes that already exist on the declaration.
2904  if (!DiagnoseMutualExclusions(S, D, Attr))
2905  return false;
2906 
2907  // This function copies an attribute Attr from a previous declaration to the
2908  // new declaration D if the new declaration doesn't itself have that attribute
2909  // yet or if that attribute allows duplicates.
2910  // If you're adding a new attribute that requires logic different from
2911  // "use explicit attribute on decl if present, else use attribute from
2912  // previous decl", for example if the attribute needs to be consistent
2913  // between redeclarations, you need to call a custom merge function here.
2914  InheritableAttr *NewAttr = nullptr;
2915  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2916  NewAttr = S.mergeAvailabilityAttr(
2917  D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2918  AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2919  AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2920  AA->getPriority());
2921  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2922  NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2923  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2924  NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2925  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2926  NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2927  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2928  NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2929  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2930  NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2931  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2932  NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2933  FA->getFirstArg());
2934  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2935  NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2936  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2937  NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2938  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2939  NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2940  IA->getInheritanceModel());
2941  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2942  NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2943  &S.Context.Idents.get(AA->getSpelling()));
2944  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2945  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2946  isa<CUDAGlobalAttr>(Attr))) {
2947  // CUDA target attributes are part of function signature for
2948  // overloading purposes and must not be merged.
2949  return false;
2950  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2951  NewAttr = S.mergeMinSizeAttr(D, *MA);
2952  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2953  NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2954  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2955  NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2956  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2957  NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2958  else if (isa<AlignedAttr>(Attr))
2959  // AlignedAttrs are handled separately, because we need to handle all
2960  // such attributes on a declaration at the same time.
2961  NewAttr = nullptr;
2962  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2963  (AMK == Sema::AMK_Override ||
2966  NewAttr = nullptr;
2967  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2968  NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2969  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2970  NewAttr = S.mergeImportModuleAttr(D, *IMA);
2971  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2972  NewAttr = S.mergeImportNameAttr(D, *INA);
2973  else if (const auto *A = dyn_cast<SYCLIntelLoopFuseAttr>(Attr))
2974  NewAttr = S.MergeSYCLIntelLoopFuseAttr(D, *A);
2975  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2976  NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2977  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2978  NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2979  else if (const auto *A = dyn_cast<IntelReqdSubGroupSizeAttr>(Attr))
2980  NewAttr = S.MergeIntelReqdSubGroupSizeAttr(D, *A);
2981  else if (const auto *A = dyn_cast<IntelNamedSubGroupSizeAttr>(Attr))
2982  NewAttr = S.MergeIntelNamedSubGroupSizeAttr(D, *A);
2983  else if (const auto *A = dyn_cast<SYCLIntelNumSimdWorkItemsAttr>(Attr))
2984  NewAttr = S.MergeSYCLIntelNumSimdWorkItemsAttr(D, *A);
2985  else if (const auto *A = dyn_cast<SYCLIntelESimdVectorizeAttr>(Attr))
2986  NewAttr = S.MergeSYCLIntelESimdVectorizeAttr(D, *A);
2987  else if (const auto *A = dyn_cast<SYCLIntelSchedulerTargetFmaxMhzAttr>(Attr))
2988  NewAttr = S.MergeSYCLIntelSchedulerTargetFmaxMhzAttr(D, *A);
2989  else if (const auto *A = dyn_cast<SYCLIntelNoGlobalWorkOffsetAttr>(Attr))
2990  NewAttr = S.MergeSYCLIntelNoGlobalWorkOffsetAttr(D, *A);
2991  else if (const auto *A = dyn_cast<SYCLIntelMaxReplicatesAttr>(Attr))
2992  NewAttr = S.MergeSYCLIntelMaxReplicatesAttr(D, *A);
2993  else if (const auto *A = dyn_cast<SYCLIntelMaxConcurrencyAttr>(Attr))
2994  NewAttr = S.MergeSYCLIntelMaxConcurrencyAttr(D, *A);
2995  else if (const auto *A = dyn_cast<SYCLIntelForcePow2DepthAttr>(Attr))
2996  NewAttr = S.MergeSYCLIntelForcePow2DepthAttr(D, *A);
2997  else if (const auto *A = dyn_cast<SYCLIntelInitiationIntervalAttr>(Attr))
2998  NewAttr = S.MergeSYCLIntelInitiationIntervalAttr(D, *A);
2999  else if (const auto *A = dyn_cast<SYCLWorkGroupSizeHintAttr>(Attr))
3000  NewAttr = S.MergeSYCLWorkGroupSizeHintAttr(D, *A);
3001  else if (const auto *A =
3002  dyn_cast<SYCLIntelMinWorkGroupsPerComputeUnitAttr>(Attr))
3004  else if (const auto *A =
3005  dyn_cast<SYCLIntelMaxWorkGroupsPerMultiprocessorAttr>(Attr))
3007  else if (const auto *A = dyn_cast<SYCLIntelMaxGlobalWorkDimAttr>(Attr))
3008  NewAttr = S.MergeSYCLIntelMaxGlobalWorkDimAttr(D, *A);
3009  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
3010  NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
3011  else if (const auto *A = dyn_cast<SYCLIntelBankWidthAttr>(Attr))
3012  NewAttr = S.MergeSYCLIntelBankWidthAttr(D, *A);
3013  else if (const auto *A = dyn_cast<SYCLIntelNumBanksAttr>(Attr))
3014  NewAttr = S.MergeSYCLIntelNumBanksAttr(D, *A);
3015  else if (const auto *A = dyn_cast<SYCLDeviceHasAttr>(Attr))
3016  NewAttr = S.MergeSYCLDeviceHasAttr(D, *A);
3017  else if (const auto *A = dyn_cast<SYCLUsesAspectsAttr>(Attr))
3018  NewAttr = S.MergeSYCLUsesAspectsAttr(D, *A);
3019  else if (const auto *A = dyn_cast<SYCLTypeAttr>(Attr))
3020  NewAttr = S.MergeSYCLTypeAttr(D, *A, A->getType());
3021  else if (const auto *A = dyn_cast<SYCLIntelPipeIOAttr>(Attr))
3022  NewAttr = S.MergeSYCLIntelPipeIOAttr(D, *A);
3023  else if (const auto *A = dyn_cast<SYCLIntelMaxWorkGroupSizeAttr>(Attr))
3024  NewAttr = S.MergeSYCLIntelMaxWorkGroupSizeAttr(D, *A);
3025  else if (const auto *A = dyn_cast<SYCLAddIRAttributesFunctionAttr>(Attr))
3026  NewAttr = S.MergeSYCLAddIRAttributesFunctionAttr(D, *A);
3027  else if (const auto *A =
3028  dyn_cast<SYCLAddIRAttributesKernelParameterAttr>(Attr))
3030  else if (const auto *A =
3031  dyn_cast<SYCLAddIRAttributesGlobalVariableAttr>(Attr))
3032  NewAttr = S.MergeSYCLAddIRAttributesGlobalVariableAttr(D, *A);
3033  else if (const auto *A = dyn_cast<SYCLAddIRAnnotationsMemberAttr>(Attr))
3034  NewAttr = S.MergeSYCLAddIRAnnotationsMemberAttr(D, *A);
3035  else if (const auto *A = dyn_cast<SYCLReqdWorkGroupSizeAttr>(Attr))
3036  NewAttr = S.MergeSYCLReqdWorkGroupSizeAttr(D, *A);
3037  else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
3038  NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
3039  NT->getZ());
3040  else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3041  NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3042  else if (isa<SuppressAttr>(Attr))
3043  // Do nothing. Each redeclaration should be suppressed separately.
3044  NewAttr = nullptr;
3045  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3046  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3047 
3048  if (NewAttr) {
3049  NewAttr->setInherited(true);
3050  D->addAttr(NewAttr);
3051  if (isa<MSInheritanceAttr>(NewAttr))
3052  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
3053  return true;
3054  }
3055 
3056  return false;
3057 }
3058 
3059 static const NamedDecl *getDefinition(const Decl *D) {
3060  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3061  return TD->getDefinition();
3062  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3063  const VarDecl *Def = VD->getDefinition();
3064  if (Def)
3065  return Def;
3066  return VD->getActingDefinition();
3067  }
3068  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3069  const FunctionDecl *Def = nullptr;
3070  if (FD->isDefined(Def, true))
3071  return Def;
3072  }
3073  return nullptr;
3074 }
3075 
3076 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3077  for (const auto *Attribute : D->attrs())
3078  if (Attribute->getKind() == Kind)
3079  return true;
3080  return false;
3081 }
3082 
3083 /// checkNewAttributesAfterDef - If we already have a definition, check that
3084 /// there are no new attributes in this declaration.
3085 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3086  if (!New->hasAttrs())
3087  return;
3088 
3089  const NamedDecl *Def = getDefinition(Old);
3090  if (!Def || Def == New)
3091  return;
3092 
3093  AttrVec &NewAttributes = New->getAttrs();
3094  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3095  const Attr *NewAttribute = NewAttributes[I];
3096 
3097  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3098  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3099  SkipBodyInfo SkipBody;
3100  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3101 
3102  // If we're skipping this definition, drop the "alias" attribute.
3103  if (SkipBody.ShouldSkip) {
3104  NewAttributes.erase(NewAttributes.begin() + I);
3105  --E;
3106  continue;
3107  }
3108  } else {
3109  VarDecl *VD = cast<VarDecl>(New);
3110  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3112  ? diag::err_alias_after_tentative
3113  : diag::err_redefinition;
3114  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3115  if (Diag == diag::err_redefinition)
3116  S.notePreviousDefinition(Def, VD->getLocation());
3117  else
3118  S.Diag(Def->getLocation(), diag::note_previous_definition);
3119  VD->setInvalidDecl();
3120  }
3121  ++I;
3122  continue;
3123  }
3124 
3125  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3126  // Tentative definitions are only interesting for the alias check above.
3127  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3128  ++I;
3129  continue;
3130  }
3131  }
3132 
3133  if (hasAttribute(Def, NewAttribute->getKind())) {
3134  ++I;
3135  continue; // regular attr merging will take care of validating this.
3136  }
3137 
3138  if (isa<C11NoReturnAttr>(NewAttribute)) {
3139  // C's _Noreturn is allowed to be added to a function after it is defined.
3140  ++I;
3141  continue;
3142  } else if (isa<UuidAttr>(NewAttribute)) {
3143  // msvc will allow a subsequent definition to add an uuid to a class
3144  ++I;
3145  continue;
3146  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3147  if (AA->isAlignas()) {
3148  // C++11 [dcl.align]p6:
3149  // if any declaration of an entity has an alignment-specifier,
3150  // every defining declaration of that entity shall specify an
3151  // equivalent alignment.
3152  // C11 6.7.5/7:
3153  // If the definition of an object does not have an alignment
3154  // specifier, any other declaration of that object shall also
3155  // have no alignment specifier.
3156  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3157  << AA;
3158  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3159  << AA;
3160  NewAttributes.erase(NewAttributes.begin() + I);
3161  --E;
3162  continue;
3163  }
3164  } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3165  // If there is a C definition followed by a redeclaration with this
3166  // attribute then there are two different definitions. In C++, prefer the
3167  // standard diagnostics.
3168  if (!S.getLangOpts().CPlusPlus) {
3169  S.Diag(NewAttribute->getLocation(),
3170  diag::err_loader_uninitialized_redeclaration);
3171  S.Diag(Def->getLocation(), diag::note_previous_definition);
3172  NewAttributes.erase(NewAttributes.begin() + I);
3173  --E;
3174  continue;
3175  }
3176  } else if (isa<SelectAnyAttr>(NewAttribute) &&
3177  cast<VarDecl>(New)->isInline() &&
3178  !cast<VarDecl>(New)->isInlineSpecified()) {
3179  // Don't warn about applying selectany to implicitly inline variables.
3180  // Older compilers and language modes would require the use of selectany
3181  // to make such variables inline, and it would have no effect if we
3182  // honored it.
3183  ++I;
3184  continue;
3185  } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3186  // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3187  // declarations after definitions.
3188  ++I;
3189  continue;
3190  }
3191 
3192  S.Diag(NewAttribute->getLocation(),
3193  diag::warn_attribute_precede_definition);
3194  S.Diag(Def->getLocation(), diag::note_previous_definition);
3195  NewAttributes.erase(NewAttributes.begin() + I);
3196  --E;
3197  }
3198 }
3199 
3200 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3201  const ConstInitAttr *CIAttr,
3202  bool AttrBeforeInit) {
3203  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3204 
3205  // Figure out a good way to write this specifier on the old declaration.
3206  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3207  // enough of the attribute list spelling information to extract that without
3208  // heroics.
3209  std::string SuitableSpelling;
3210  if (S.getLangOpts().CPlusPlus20)
3211  SuitableSpelling = std::string(
3212  S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3213  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3214  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3215  InsertLoc, {tok::l_square, tok::l_square,
3216  S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3217  S.PP.getIdentifierInfo("require_constant_initialization"),
3218  tok::r_square, tok::r_square}));
3219  if (SuitableSpelling.empty())
3220  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3221  InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3222  S.PP.getIdentifierInfo("require_constant_initialization"),
3223  tok::r_paren, tok::r_paren}));
3224  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3225  SuitableSpelling = "constinit";
3226  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3227  SuitableSpelling = "[[clang::require_constant_initialization]]";
3228  if (SuitableSpelling.empty())
3229  SuitableSpelling = "__attribute__((require_constant_initialization))";
3230  SuitableSpelling += " ";
3231 
3232  if (AttrBeforeInit) {
3233  // extern constinit int a;
3234  // int a = 0; // error (missing 'constinit'), accepted as extension
3235  assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3236  S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3237  << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3238  S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3239  } else {
3240  // int a = 0;
3241  // constinit extern int a; // error (missing 'constinit')
3242  S.Diag(CIAttr->getLocation(),
3243  CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3244  : diag::warn_require_const_init_added_too_late)
3245  << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3246  S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3247  << CIAttr->isConstinit()
3248  << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3249  }
3250 }
3251 
3252 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3254  AvailabilityMergeKind AMK) {
3255  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3256  UsedAttr *NewAttr = OldAttr->clone(Context);
3257  NewAttr->setInherited(true);
3258  New->addAttr(NewAttr);
3259  }
3260  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3261  RetainAttr *NewAttr = OldAttr->clone(Context);
3262  NewAttr->setInherited(true);
3263  New->addAttr(NewAttr);
3264  }
3265 
3266  if (!Old->hasAttrs() && !New->hasAttrs())
3267  return;
3268 
3269  // [dcl.constinit]p1:
3270  // If the [constinit] specifier is applied to any declaration of a
3271  // variable, it shall be applied to the initializing declaration.
3272  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3273  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3274  if (bool(OldConstInit) != bool(NewConstInit)) {
3275  const auto *OldVD = cast<VarDecl>(Old);
3276  auto *NewVD = cast<VarDecl>(New);
3277 
3278  // Find the initializing declaration. Note that we might not have linked
3279  // the new declaration into the redeclaration chain yet.
3280  const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3281  if (!InitDecl &&
3282  (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3283  InitDecl = NewVD;
3284 
3285  if (InitDecl == NewVD) {
3286  // This is the initializing declaration. If it would inherit 'constinit',
3287  // that's ill-formed. (Note that we do not apply this to the attribute
3288  // form).
3289  if (OldConstInit && OldConstInit->isConstinit())
3290  diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3291  /*AttrBeforeInit=*/true);
3292  } else if (NewConstInit) {
3293  // This is the first time we've been told that this declaration should
3294  // have a constant initializer. If we already saw the initializing
3295  // declaration, this is too late.
3296  if (InitDecl && InitDecl != NewVD) {
3297  diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3298  /*AttrBeforeInit=*/false);
3299  NewVD->dropAttr<ConstInitAttr>();
3300  }
3301  }
3302  }
3303 
3304  // Attributes declared post-definition are currently ignored.
3305  checkNewAttributesAfterDef(*this, New, Old);
3306 
3307  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3308  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3309  if (!OldA->isEquivalent(NewA)) {
3310  // This redeclaration changes __asm__ label.
3311  Diag(New->getLocation(), diag::err_different_asm_label);
3312  Diag(OldA->getLocation(), diag::note_previous_declaration);
3313  }
3314  } else if (Old->isUsed()) {
3315  // This redeclaration adds an __asm__ label to a declaration that has
3316  // already been ODR-used.
3317  Diag(New->getLocation(), diag::err_late_asm_label_name)
3318  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3319  }
3320  }
3321 
3322  // Re-declaration cannot add abi_tag's.
3323  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3324  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3325  for (const auto &NewTag : NewAbiTagAttr->tags()) {
3326  if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3327  Diag(NewAbiTagAttr->getLocation(),
3328  diag::err_new_abi_tag_on_redeclaration)
3329  << NewTag;
3330  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3331  }
3332  }
3333  } else {
3334  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3335  Diag(Old->getLocation(), diag::note_previous_declaration);
3336  }
3337  }
3338 
3339  // This redeclaration adds a section attribute.
3340  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3341  if (auto *VD = dyn_cast<VarDecl>(New)) {
3342  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3343  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3344  Diag(Old->getLocation(), diag::note_previous_declaration);
3345  }
3346  }
3347  }
3348 
3349  // Redeclaration adds code-seg attribute.
3350  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3351  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3352  !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3353  Diag(New->getLocation(), diag::warn_mismatched_section)
3354  << 0 /*codeseg*/;
3355  Diag(Old->getLocation(), diag::note_previous_declaration);
3356  }
3357 
3358  if (!Old->hasAttrs())
3359  return;
3360 
3361  bool foundAny = New->hasAttrs();
3362 
3363  // Ensure that any moving of objects within the allocated map is done before
3364  // we process them.
3365  if (!foundAny) New->setAttrs(AttrVec());
3366 
3367  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3368  // Ignore deprecated/unavailable/availability attributes if requested.
3369  AvailabilityMergeKind LocalAMK = AMK_None;
3370  if (isa<DeprecatedAttr>(I) ||
3371  isa<UnavailableAttr>(I) ||
3372  isa<AvailabilityAttr>(I)) {
3373  switch (AMK) {
3374  case AMK_None:
3375  continue;
3376 
3377  case AMK_Redeclaration:
3378  case AMK_Override:
3379  case AMK_ProtocolImplementation:
3380  case AMK_OptionalProtocolImplementation:
3381  LocalAMK = AMK;
3382  break;
3383  }
3384  }
3385 
3386  // Already handled.
3387  if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3388  continue;
3389 
3390  if (mergeDeclAttribute(*this, New, I, LocalAMK))
3391  foundAny = true;
3392  }
3393 
3394  if (mergeAlignedAttrs(*this, New, Old))
3395  foundAny = true;
3396 
3397  if (!foundAny) New->dropAttrs();
3398 }
3399 
3400 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3401 /// to the new one.
3403  const ParmVarDecl *oldDecl,
3404  Sema &S) {
3405  // C++11 [dcl.attr.depend]p2:
3406  // The first declaration of a function shall specify the
3407  // carries_dependency attribute for its declarator-id if any declaration
3408  // of the function specifies the carries_dependency attribute.
3409  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3410  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3411  S.Diag(CDA->getLocation(),
3412  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3413  // Find the first declaration of the parameter.
3414  // FIXME: Should we build redeclaration chains for function parameters?
3415  const FunctionDecl *FirstFD =
3416  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3417  const ParmVarDecl *FirstVD =
3418  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3419  S.Diag(FirstVD->getLocation(),
3420  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3421  }
3422 
3423  // HLSL parameter declarations for inout and out must match between
3424  // declarations. In HLSL inout and out are ambiguous at the call site, but
3425  // have different calling behavior, so you cannot overload a method based on a
3426  // difference between inout and out annotations.
3427  if (S.getLangOpts().HLSL) {
3428  const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3429  const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3430  // We don't need to cover the case where one declaration doesn't have an
3431  // attribute. The only possible case there is if one declaration has an `in`
3432  // attribute and the other declaration has no attribute. This case is
3433  // allowed since parameters are `in` by default.
3434  if (NDAttr && ODAttr &&
3435  NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3436  S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3437  << NDAttr << newDecl;
3438  S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3439  << ODAttr;
3440  }
3441  }
3442 
3443  if (!oldDecl->hasAttrs())
3444  return;
3445 
3446  bool foundAny = newDecl->hasAttrs();
3447 
3448  // Ensure that any moving of objects within the allocated map is
3449  // done before we process them.
3450  if (!foundAny) newDecl->setAttrs(AttrVec());
3451 
3452  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3453  if (!DeclHasAttr(newDecl, I)) {
3454  InheritableAttr *newAttr =
3455  cast<InheritableParamAttr>(I->clone(S.Context));
3456  newAttr->setInherited(true);
3457  newDecl->addAttr(newAttr);
3458  foundAny = true;
3459  }
3460  }
3461 
3462  if (!foundAny) newDecl->dropAttrs();
3463 }
3464 
3466  const ASTContext &Ctx) {
3467 
3468  auto NoSizeInfo = [&Ctx](QualType Ty) {
3469  if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3470  return true;
3471  if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3472  return VAT->getSizeModifier() == ArraySizeModifier::Star;
3473  return false;
3474  };
3475 
3476  // `type[]` is equivalent to `type *` and `type[*]`.
3477  if (NoSizeInfo(Old) && NoSizeInfo(New))
3478  return true;
3479 
3480  // Don't try to compare VLA sizes, unless one of them has the star modifier.
3481  if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3482  const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3483  const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3484  if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3485  (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3486  return false;
3487  return true;
3488  }
3489 
3490  // Only compare size, ignore Size modifiers and CVR.
3491  if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3492  return Ctx.getAsConstantArrayType(Old)->getSize() ==
3493  Ctx.getAsConstantArrayType(New)->getSize();
3494  }
3495 
3496  // Don't try to compare dependent sized array
3498  return true;
3499  }
3500 
3501  return Old == New;
3502 }
3503 
3504 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3505  const ParmVarDecl *OldParam,
3506  Sema &S) {
3507  if (auto Oldnullability = OldParam->getType()->getNullability()) {
3508  if (auto Newnullability = NewParam->getType()->getNullability()) {
3509  if (*Oldnullability != *Newnullability) {
3510  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3512  *Newnullability,
3514  != 0))
3516  *Oldnullability,
3518  != 0));
3519  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3520  }
3521  } else {
3522  QualType NewT = NewParam->getType();
3523  NewT = S.Context.getAttributedType(
3524  AttributedType::getNullabilityAttrKind(*Oldnullability),
3525  NewT, NewT);
3526  NewParam->setType(NewT);
3527  }
3528  }
3529  const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3530  const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3531  if (OldParamDT && NewParamDT &&
3532  OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3533  QualType OldParamOT = OldParamDT->getOriginalType();
3534  QualType NewParamOT = NewParamDT->getOriginalType();
3535  if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3536  S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3537  << NewParam << NewParamOT;
3538  S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3539  << OldParamOT;
3540  }
3541  }
3542 }
3543 
3544 namespace {
3545 
3546 /// Used in MergeFunctionDecl to keep track of function parameters in
3547 /// C.
3548 struct GNUCompatibleParamWarning {
3549  ParmVarDecl *OldParm;
3550  ParmVarDecl *NewParm;
3551  QualType PromotedType;
3552 };
3553 
3554 } // end anonymous namespace
3555 
3556 // Determine whether the previous declaration was a definition, implicit
3557 // declaration, or a declaration.
3558 template <typename T>
3559 static std::pair<diag::kind, SourceLocation>
3560 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3561  diag::kind PrevDiag;
3562  SourceLocation OldLocation = Old->getLocation();
3563  if (Old->isThisDeclarationADefinition())
3564  PrevDiag = diag::note_previous_definition;
3565  else if (Old->isImplicit()) {
3566  PrevDiag = diag::note_previous_implicit_declaration;
3567  if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3568  if (FD->getBuiltinID())
3569  PrevDiag = diag::note_previous_builtin_declaration;
3570  }
3571  if (OldLocation.isInvalid())
3572  OldLocation = New->getLocation();
3573  } else
3574  PrevDiag = diag::note_previous_declaration;
3575  return std::make_pair(PrevDiag, OldLocation);
3576 }
3577 
3578 /// canRedefineFunction - checks if a function can be redefined. Currently,
3579 /// only extern inline functions can be redefined, and even then only in
3580 /// GNU89 mode.
3581 static bool canRedefineFunction(const FunctionDecl *FD,
3582  const LangOptions& LangOpts) {
3583  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3584  !LangOpts.CPlusPlus &&
3585  FD->isInlineSpecified() &&
3586  FD->getStorageClass() == SC_Extern);
3587 }
3588 
3590  const AttributedType *AT = T->getAs<AttributedType>();
3591  while (AT && !AT->isCallingConv())
3592  AT = AT->getModifiedType()->getAs<AttributedType>();
3593  return AT;
3594 }
3595 
3596 template <typename T>
3597 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3598  const DeclContext *DC = Old->getDeclContext();
3599  if (DC->isRecord())
3600  return false;
3601 
3602  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3603  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3604  return true;
3605  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3606  return true;
3607  return false;
3608 }
3609 
3610 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3611 static bool isExternC(VarTemplateDecl *) { return false; }
3612 static bool isExternC(FunctionTemplateDecl *) { return false; }
3613 
3614 /// Check whether a redeclaration of an entity introduced by a
3615 /// using-declaration is valid, given that we know it's not an overload
3616 /// (nor a hidden tag declaration).
3617 template<typename ExpectedDecl>
3619  ExpectedDecl *New) {
3620  // C++11 [basic.scope.declarative]p4:
3621  // Given a set of declarations in a single declarative region, each of
3622  // which specifies the same unqualified name,
3623  // -- they shall all refer to the same entity, or all refer to functions
3624  // and function templates; or
3625  // -- exactly one declaration shall declare a class name or enumeration
3626  // name that is not a typedef name and the other declarations shall all
3627  // refer to the same variable or enumerator, or all refer to functions
3628  // and function templates; in this case the class name or enumeration
3629  // name is hidden (3.3.10).
3630 
3631  // C++11 [namespace.udecl]p14:
3632  // If a function declaration in namespace scope or block scope has the
3633  // same name and the same parameter-type-list as a function introduced
3634  // by a using-declaration, and the declarations do not declare the same
3635  // function, the program is ill-formed.
3636 
3637  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3638  if (Old &&
3639  !Old->getDeclContext()->getRedeclContext()->Equals(
3640  New->getDeclContext()->getRedeclContext()) &&
3641  !(isExternC(Old) && isExternC(New)))
3642  Old = nullptr;
3643 
3644  if (!Old) {
3645  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3646  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3647  S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3648  return true;
3649  }
3650  return false;
3651 }
3652 
3654  const FunctionDecl *B) {
3655  assert(A->getNumParams() == B->getNumParams());
3656 
3657  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3658  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3659  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3660  if (AttrA == AttrB)
3661  return true;
3662  return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3663  AttrA->isDynamic() == AttrB->isDynamic();
3664  };
3665 
3666  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3667 }
3668 
3669 /// If necessary, adjust the semantic declaration context for a qualified
3670 /// declaration to name the correct inline namespace within the qualifier.
3672  DeclaratorDecl *OldD) {
3673  // The only case where we need to update the DeclContext is when
3674  // redeclaration lookup for a qualified name finds a declaration
3675  // in an inline namespace within the context named by the qualifier:
3676  //
3677  // inline namespace N { int f(); }
3678  // int ::f(); // Sema DC needs adjusting from :: to N::.
3679  //
3680  // For unqualified declarations, the semantic context *can* change
3681  // along the redeclaration chain (for local extern declarations,
3682  // extern "C" declarations, and friend declarations in particular).
3683  if (!NewD->getQualifier())
3684  return;
3685 
3686  // NewD is probably already in the right context.
3687  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3688  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3689  if (NamedDC->Equals(SemaDC))
3690  return;
3691 
3692  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3693  NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3694  "unexpected context for redeclaration");
3695 
3696  auto *LexDC = NewD->getLexicalDeclContext();
3697  auto FixSemaDC = [=](NamedDecl *D) {
3698  if (!D)
3699  return;
3700  D->setDeclContext(SemaDC);
3701  D->setLexicalDeclContext(LexDC);
3702  };
3703 
3704  FixSemaDC(NewD);
3705  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3706  FixSemaDC(FD->getDescribedFunctionTemplate());
3707  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3708  FixSemaDC(VD->getDescribedVarTemplate());
3709 }
3710 
3711 /// MergeFunctionDecl - We just parsed a function 'New' from
3712 /// declarator D which has the same name and scope as a previous
3713 /// declaration 'Old'. Figure out how to resolve this situation,
3714 /// merging decls or emitting diagnostics as appropriate.
3715 ///
3716 /// In C++, New and Old must be declarations that are not
3717 /// overloaded. Use IsOverload to determine whether New and Old are
3718 /// overloaded, and to select the Old declaration that New should be
3719 /// merged with.
3720 ///
3721 /// Returns true if there was an error, false otherwise.
3723  bool MergeTypeWithOld, bool NewDeclIsDefn) {
3724  // Verify the old decl was also a function.
3725  FunctionDecl *Old = OldD->getAsFunction();
3726  if (!Old) {
3727  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3728  if (New->getFriendObjectKind()) {
3729  Diag(New->getLocation(), diag::err_using_decl_friend);
3730  Diag(Shadow->getTargetDecl()->getLocation(),
3731  diag::note_using_decl_target);
3732  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3733  << 0;
3734  return true;
3735  }
3736 
3737  // Check whether the two declarations might declare the same function or
3738  // function template.
3739  if (FunctionTemplateDecl *NewTemplate =
3741  if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3742  NewTemplate))
3743  return true;
3744  OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3745  ->getAsFunction();
3746  } else {
3747  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3748  return true;
3749  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3750  }
3751  } else {
3752  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3753  << New->getDeclName();
3754  notePreviousDefinition(OldD, New->getLocation());
3755  return true;
3756  }
3757  }
3758 
3759  // If the old declaration was found in an inline namespace and the new
3760  // declaration was qualified, update the DeclContext to match.
3762 
3763  // If the old declaration is invalid, just give up here.
3764  if (Old->isInvalidDecl())
3765  return true;
3766 
3767  // Disallow redeclaration of some builtins.
3768  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3769  Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3770  Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3771  << Old << Old->getType();
3772  return true;
3773  }
3774 
3775  diag::kind PrevDiag;
3776  SourceLocation OldLocation;
3777  std::tie(PrevDiag, OldLocation) =
3779 
3780  // Don't complain about this if we're in GNU89 mode and the old function
3781  // is an extern inline function.
3782  // Don't complain about specializations. They are not supposed to have
3783  // storage classes.
3784  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3785  New->getStorageClass() == SC_Static &&
3786  Old->hasExternalFormalLinkage() &&
3788  !canRedefineFunction(Old, getLangOpts())) {
3789  if (getLangOpts().MicrosoftExt) {
3790  Diag(New->getLocation(), diag::ext_static_non_static) << New;
3791  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3792  } else {
3793  Diag(New->getLocation(), diag::err_static_non_static) << New;
3794  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3795  return true;
3796  }
3797  }
3798 
3799  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3800  if (!Old->hasAttr<InternalLinkageAttr>()) {
3801  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3802  << ILA;
3803  Diag(Old->getLocation(), diag::note_previous_declaration);
3804  New->dropAttr<InternalLinkageAttr>();
3805  }
3806 
3807  if (auto *EA = New->getAttr<ErrorAttr>()) {
3808  if (!Old->hasAttr<ErrorAttr>()) {
3809  Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3810  Diag(Old->getLocation(), diag::note_previous_declaration);
3811  New->dropAttr<ErrorAttr>();
3812  }
3813  }
3814 
3815  if (CheckRedeclarationInModule(New, Old))
3816  return true;
3817 
3818  if (!getLangOpts().CPlusPlus) {
3819  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3820  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3821  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3822  << New << OldOvl;
3823 
3824  // Try our best to find a decl that actually has the overloadable
3825  // attribute for the note. In most cases (e.g. programs with only one
3826  // broken declaration/definition), this won't matter.
3827  //
3828  // FIXME: We could do this if we juggled some extra state in
3829  // OverloadableAttr, rather than just removing it.
3830  const Decl *DiagOld = Old;
3831  if (OldOvl) {
3832  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3833  const auto *A = D->getAttr<OverloadableAttr>();
3834  return A && !A->isImplicit();
3835  });
3836  // If we've implicitly added *all* of the overloadable attrs to this
3837  // chain, emitting a "previous redecl" note is pointless.
3838  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3839  }
3840 
3841  if (DiagOld)
3842  Diag(DiagOld->getLocation(),
3843  diag::note_attribute_overloadable_prev_overload)
3844  << OldOvl;
3845 
3846  if (OldOvl)
3847  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3848  else
3849  New->dropAttr<OverloadableAttr>();
3850  }
3851  }
3852 
3853  // It is not permitted to redeclare an SME function with different SME
3854  // attributes.
3855  if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3856  Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3857  << New->getType() << Old->getType();
3858  Diag(OldLocation, diag::note_previous_declaration);
3859  return true;
3860  }
3861 
3862  // If a function is first declared with a calling convention, but is later
3863  // declared or defined without one, all following decls assume the calling
3864  // convention of the first.
3865  //
3866  // It's OK if a function is first declared without a calling convention,
3867  // but is later declared or defined with the default calling convention.
3868  //
3869  // To test if either decl has an explicit calling convention, we look for
3870  // AttributedType sugar nodes on the type as written. If they are missing or
3871  // were canonicalized away, we assume the calling convention was implicit.
3872  //
3873  // Note also that we DO NOT return at this point, because we still have
3874  // other tests to run.
3875  QualType OldQType = Context.getCanonicalType(Old->getType());
3876  QualType NewQType = Context.getCanonicalType(New->getType());
3877  const FunctionType *OldType = cast<FunctionType>(OldQType);
3878  const FunctionType *NewType = cast<FunctionType>(NewQType);
3879  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3880  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3881  bool RequiresAdjustment = false;
3882 
3883  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3884  FunctionDecl *First = Old->getFirstDecl();
3885  const FunctionType *FT =
3886  First->getType().getCanonicalType()->castAs<FunctionType>();
3887  FunctionType::ExtInfo FI = FT->getExtInfo();
3888  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3889  if (!NewCCExplicit) {
3890  // Inherit the CC from the previous declaration if it was specified
3891  // there but not here.
3892  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3893  RequiresAdjustment = true;
3894  } else if (Old->getBuiltinID()) {
3895  // Builtin attribute isn't propagated to the new one yet at this point,
3896  // so we check if the old one is a builtin.
3897 
3898  // Calling Conventions on a Builtin aren't really useful and setting a
3899  // default calling convention and cdecl'ing some builtin redeclarations is
3900  // common, so warn and ignore the calling convention on the redeclaration.
3901  Diag(New->getLocation(), diag::warn_cconv_unsupported)
3902  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3903  << (int)CallingConventionIgnoredReason::BuiltinFunction;
3904  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3905  RequiresAdjustment = true;
3906  } else {
3907  // Calling conventions aren't compatible, so complain.
3908  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3909  Diag(New->getLocation(), diag::err_cconv_change)
3910  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3911  << !FirstCCExplicit
3912  << (!FirstCCExplicit ? "" :
3913  FunctionType::getNameForCallConv(FI.getCC()));
3914 
3915  // Put the note on the first decl, since it is the one that matters.
3916  Diag(First->getLocation(), diag::note_previous_declaration);
3917  return true;
3918  }
3919  }
3920 
3921  // FIXME: diagnose the other way around?
3922  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3923  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3924  RequiresAdjustment = true;
3925  }
3926 
3927  // Merge regparm attribute.
3928  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3929  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3930  if (NewTypeInfo.getHasRegParm()) {
3931  Diag(New->getLocation(), diag::err_regparm_mismatch)
3932  << NewType->getRegParmType()
3933  << OldType->getRegParmType();
3934  Diag(OldLocation, diag::note_previous_declaration);
3935  return true;
3936  }
3937 
3938  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3939  RequiresAdjustment = true;
3940  }
3941 
3942  // Merge ns_returns_retained attribute.
3943  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3944  if (NewTypeInfo.getProducesResult()) {
3945  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3946  << "'ns_returns_retained'";
3947  Diag(OldLocation, diag::note_previous_declaration);
3948  return true;
3949  }
3950 
3951  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3952  RequiresAdjustment = true;
3953  }
3954 
3955  if (OldTypeInfo.getNoCallerSavedRegs() !=
3956  NewTypeInfo.getNoCallerSavedRegs()) {
3957  if (NewTypeInfo.getNoCallerSavedRegs()) {
3958  AnyX86NoCallerSavedRegistersAttr *Attr =
3959  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3960  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3961  Diag(OldLocation, diag::note_previous_declaration);
3962  return true;
3963  }
3964 
3965  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3966  RequiresAdjustment = true;
3967  }
3968 
3969  if (RequiresAdjustment) {
3970  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3971  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3972  New->setType(QualType(AdjustedType, 0));
3973  NewQType = Context.getCanonicalType(New->getType());
3974  }
3975 
3976  // If this redeclaration makes the function inline, we may need to add it to
3977  // UndefinedButUsed.
3978  if (!Old->isInlined() && New->isInlined() &&
3979  !New->hasAttr<GNUInlineAttr>() &&
3980  !getLangOpts().GNUInline &&
3981  Old->isUsed(false) &&
3982  !Old->isDefined() && !New->isThisDeclarationADefinition())
3983  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3984  SourceLocation()));
3985 
3986  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3987  // about it.
3988  if (New->hasAttr<GNUInlineAttr>() &&
3989  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3990  UndefinedButUsed.erase(Old->getCanonicalDecl());
3991  }
3992 
3993  // If pass_object_size params don't match up perfectly, this isn't a valid
3994  // redeclaration.
3995  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3996  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3997  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3998  << New->getDeclName();
3999  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4000  return true;
4001  }
4002 
4003  if (getLangOpts().CPlusPlus) {
4004  OldQType = Context.getCanonicalType(Old->getType());
4005  NewQType = Context.getCanonicalType(New->getType());
4006 
4007  // Go back to the type source info to compare the declared return types,
4008  // per C++1y [dcl.type.auto]p13:
4009  // Redeclarations or specializations of a function or function template
4010  // with a declared return type that uses a placeholder type shall also
4011  // use that placeholder, not a deduced type.
4012  QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4013  QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4014  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4015  canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4016  OldDeclaredReturnType)) {
4017  QualType ResQT;
4018  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4019  OldDeclaredReturnType->isObjCObjectPointerType())
4020  // FIXME: This does the wrong thing for a deduced return type.
4021  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4022  if (ResQT.isNull()) {
4023  if (New->isCXXClassMember() && New->isOutOfLine())
4024  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4025  << New << New->getReturnTypeSourceRange();
4026  else
4027  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4028  << New->getReturnTypeSourceRange();
4029  Diag(OldLocation, PrevDiag) << Old << Old->getType()
4030  << Old->getReturnTypeSourceRange();
4031  return true;
4032  }
4033  else
4034  NewQType = ResQT;
4035  }
4036 
4037  QualType OldReturnType = OldType->getReturnType();
4038  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4039  if (OldReturnType != NewReturnType) {
4040  // If this function has a deduced return type and has already been
4041  // defined, copy the deduced value from the old declaration.
4042  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4043  if (OldAT && OldAT->isDeduced()) {
4044  QualType DT = OldAT->getDeducedType();
4045  if (DT.isNull()) {
4046  New->setType(SubstAutoTypeDependent(New->getType()));
4047  NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4048  } else {
4049  New->setType(SubstAutoType(New->getType(), DT));
4050  NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4051  }
4052  }
4053  }
4054 
4055  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4056  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4057  if (OldMethod && NewMethod) {
4058  // Preserve triviality.
4059  NewMethod->setTrivial(OldMethod->isTrivial());
4060 
4061  // MSVC allows explicit template specialization at class scope:
4062  // 2 CXXMethodDecls referring to the same function will be injected.
4063  // We don't want a redeclaration error.
4064  bool IsClassScopeExplicitSpecialization =
4065  OldMethod->isFunctionTemplateSpecialization() &&
4066  NewMethod->isFunctionTemplateSpecialization();
4067  bool isFriend = NewMethod->getFriendObjectKind();
4068 
4069  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4070  !IsClassScopeExplicitSpecialization) {
4071  // -- Member function declarations with the same name and the
4072  // same parameter types cannot be overloaded if any of them
4073  // is a static member function declaration.
4074  if (OldMethod->isStatic() != NewMethod->isStatic()) {
4075  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4076  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4077  return true;
4078  }
4079 
4080  // C++ [class.mem]p1:
4081  // [...] A member shall not be declared twice in the
4082  // member-specification, except that a nested class or member
4083  // class template can be declared and then later defined.
4084  if (!inTemplateInstantiation()) {
4085  unsigned NewDiag;
4086  if (isa<CXXConstructorDecl>(OldMethod))
4087  NewDiag = diag::err_constructor_redeclared;
4088  else if (isa<CXXDestructorDecl>(NewMethod))
4089  NewDiag = diag::err_destructor_redeclared;
4090  else if (isa<CXXConversionDecl>(NewMethod))
4091  NewDiag = diag::err_conv_function_redeclared;
4092  else
4093  NewDiag = diag::err_member_redeclared;
4094 
4095  Diag(New->getLocation(), NewDiag);
4096  } else {
4097  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4098  << New << New->getType();
4099  }
4100  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4101  return true;
4102 
4103  // Complain if this is an explicit declaration of a special
4104  // member that was initially declared implicitly.
4105  //
4106  // As an exception, it's okay to befriend such methods in order
4107  // to permit the implicit constructor/destructor/operator calls.
4108  } else if (OldMethod->isImplicit()) {
4109  if (isFriend) {
4110  NewMethod->setImplicit();
4111  } else {
4112  Diag(NewMethod->getLocation(),
4113  diag::err_definition_of_implicitly_declared_member)
4114  << New << llvm::to_underlying(getSpecialMember(OldMethod));
4115  return true;
4116  }
4117  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4118  Diag(NewMethod->getLocation(),
4119  diag::err_definition_of_explicitly_defaulted_member)
4120  << llvm::to_underlying(getSpecialMember(OldMethod));
4121  return true;
4122  }
4123  }
4124 
4125  // C++1z [over.load]p2
4126  // Certain function declarations cannot be overloaded:
4127  // -- Function declarations that differ only in the return type,
4128  // the exception specification, or both cannot be overloaded.
4129 
4130  // Check the exception specifications match. This may recompute the type of
4131  // both Old and New if it resolved exception specifications, so grab the
4132  // types again after this. Because this updates the type, we do this before
4133  // any of the other checks below, which may update the "de facto" NewQType
4134  // but do not necessarily update the type of New.
4135  if (CheckEquivalentExceptionSpec(Old, New))
4136  return true;
4137 
4138  // C++11 [dcl.attr.noreturn]p1:
4139  // The first declaration of a function shall specify the noreturn
4140  // attribute if any declaration of that function specifies the noreturn
4141  // attribute.
4142  if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4143  if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4144  Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4145  << NRA;
4146  Diag(Old->getLocation(), diag::note_previous_declaration);
4147  }
4148 
4149  // C++11 [dcl.attr.depend]p2:
4150  // The first declaration of a function shall specify the
4151  // carries_dependency attribute for its declarator-id if any declaration
4152  // of the function specifies the carries_dependency attribute.
4153  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4154  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4155  Diag(CDA->getLocation(),
4156  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4157  Diag(Old->getFirstDecl()->getLocation(),
4158  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4159  }
4160 
4161  // (C++98 8.3.5p3):
4162  // All declarations for a function shall agree exactly in both the
4163  // return type and the parameter-type-list.
4164  // We also want to respect all the extended bits except noreturn.
4165 
4166  // noreturn should now match unless the old type info didn't have it.
4167  QualType OldQTypeForComparison = OldQType;
4168  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4169  auto *OldType = OldQType->castAs<FunctionProtoType>();
4170  const FunctionType *OldTypeForComparison
4171  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4172  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4173  assert(OldQTypeForComparison.isCanonical());
4174  }
4175 
4176  if (haveIncompatibleLanguageLinkages(Old, New)) {
4177  // As a special case, retain the language linkage from previous
4178  // declarations of a friend function as an extension.
4179  //
4180  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4181  // and is useful because there's otherwise no way to specify language
4182  // linkage within class scope.
4183  //
4184  // Check cautiously as the friend object kind isn't yet complete.
4185  if (New->getFriendObjectKind() != Decl::FOK_None) {
4186  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4187  Diag(OldLocation, PrevDiag);
4188  } else {
4189  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4190  Diag(OldLocation, PrevDiag);
4191  return true;
4192  }
4193  }
4194 
4195  // If the function types are compatible, merge the declarations. Ignore the
4196  // exception specifier because it was already checked above in
4197  // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4198  // about incompatible types under -fms-compatibility.
4199  if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4200  NewQType))
4201  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4202 
4203  // If the types are imprecise (due to dependent constructs in friends or
4204  // local extern declarations), it's OK if they differ. We'll check again
4205  // during instantiation.
4206  if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4207  return false;
4208 
4209  // Fall through for conflicting redeclarations and redefinitions.
4210  }
4211 
4212  // C: Function types need to be compatible, not identical. This handles
4213  // duplicate function decls like "void f(int); void f(enum X);" properly.
4214  if (!getLangOpts().CPlusPlus) {
4215  // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4216  // type is specified by a function definition that contains a (possibly
4217  // empty) identifier list, both shall agree in the number of parameters
4218  // and the type of each parameter shall be compatible with the type that
4219  // results from the application of default argument promotions to the
4220  // type of the corresponding identifier. ...
4221  // This cannot be handled by ASTContext::typesAreCompatible() because that
4222  // doesn't know whether the function type is for a definition or not when
4223  // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4224  // we need to cover here is that the number of arguments agree as the
4225  // default argument promotion rules were already checked by
4226  // ASTContext::typesAreCompatible().
4227  if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4228  Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4229  if (Old->hasInheritedPrototype())
4230  Old = Old->getCanonicalDecl();
4231  Diag(New->getLocation(), diag::err_conflicting_types) << New;
4232  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4233  return true;
4234  }
4235 
4236  // If we are merging two functions where only one of them has a prototype,
4237  // we may have enough information to decide to issue a diagnostic that the
4238  // function without a protoype will change behavior in C23. This handles
4239  // cases like:
4240  // void i(); void i(int j);
4241  // void i(int j); void i();
4242  // void i(); void i(int j) {}
4243  // See ActOnFinishFunctionBody() for other cases of the behavior change
4244  // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4245  // type without a prototype.
4246  if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4247  !New->isImplicit() && !Old->isImplicit()) {
4248  const FunctionDecl *WithProto, *WithoutProto;
4249  if (New->hasWrittenPrototype()) {
4250  WithProto = New;
4251  WithoutProto = Old;
4252  } else {
4253  WithProto = Old;
4254  WithoutProto = New;
4255  }
4256 
4257  if (WithProto->getNumParams() != 0) {
4258  if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4259  // The one without the prototype will be changing behavior in C23, so
4260  // warn about that one so long as it's a user-visible declaration.
4261  bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4262  if (WithoutProto == New)
4263  IsWithoutProtoADef = NewDeclIsDefn;
4264  else
4265  IsWithProtoADef = NewDeclIsDefn;
4266  Diag(WithoutProto->getLocation(),
4267  diag::warn_non_prototype_changes_behavior)
4268  << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4269  << (WithoutProto == Old) << IsWithProtoADef;
4270 
4271  // The reason the one without the prototype will be changing behavior
4272  // is because of the one with the prototype, so note that so long as
4273  // it's a user-visible declaration. There is one exception to this:
4274  // when the new declaration is a definition without a prototype, the
4275  // old declaration with a prototype is not the cause of the issue,
4276  // and that does not need to be noted because the one with a
4277  // prototype will not change behavior in C23.
4278  if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4279  !IsWithoutProtoADef)
4280  Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4281  }
4282  }
4283  }
4284 
4285  if (Context.typesAreCompatible(OldQType, NewQType)) {
4286  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4287  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4288  const FunctionProtoType *OldProto = nullptr;
4289  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4290  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4291  // The old declaration provided a function prototype, but the
4292  // new declaration does not. Merge in the prototype.
4293  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4294  NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4295  OldProto->getParamTypes(),
4296  OldProto->getExtProtoInfo());
4297  New->setType(NewQType);
4298  New->setHasInheritedPrototype();
4299 
4300  // Synthesize parameters with the same types.
4302  for (const auto &ParamType : OldProto->param_types()) {
4304  Context, New, SourceLocation(), SourceLocation(), nullptr,
4305  ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4306  Param->setScopeInfo(0, Params.size());
4307  Param->setImplicit();
4308  Params.push_back(Param);
4309  }
4310 
4311  New->setParams(Params);
4312  }
4313 
4314  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4315  }
4316  }
4317 
4318  // Check if the function types are compatible when pointer size address
4319  // spaces are ignored.
4320  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4321  return false;
4322 
4323  // GNU C permits a K&R definition to follow a prototype declaration
4324  // if the declared types of the parameters in the K&R definition
4325  // match the types in the prototype declaration, even when the
4326  // promoted types of the parameters from the K&R definition differ
4327  // from the types in the prototype. GCC then keeps the types from
4328  // the prototype.
4329  //
4330  // If a variadic prototype is followed by a non-variadic K&R definition,
4331  // the K&R definition becomes variadic. This is sort of an edge case, but
4332  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4333  // C99 6.9.1p8.
4334  if (!getLangOpts().CPlusPlus &&
4335  Old->hasPrototype() && !New->hasPrototype() &&
4336  New->getType()->getAs<FunctionProtoType>() &&
4337  Old->getNumParams() == New->getNumParams()) {
4338  SmallVector<QualType, 16> ArgTypes;
4340  const FunctionProtoType *OldProto
4341  = Old->getType()->getAs<FunctionProtoType>();
4342  const FunctionProtoType *NewProto
4343  = New->getType()->getAs<FunctionProtoType>();
4344 
4345  // Determine whether this is the GNU C extension.
4346  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4347  NewProto->getReturnType());
4348  bool LooseCompatible = !MergedReturn.isNull();
4349  for (unsigned Idx = 0, End = Old->getNumParams();
4350  LooseCompatible && Idx != End; ++Idx) {
4351  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4352  ParmVarDecl *NewParm = New->getParamDecl(Idx);
4353  if (Context.typesAreCompatible(OldParm->getType(),
4354  NewProto->getParamType(Idx))) {
4355  ArgTypes.push_back(NewParm->getType());
4356  } else if (Context.typesAreCompatible(OldParm->getType(),
4357  NewParm->getType(),
4358  /*CompareUnqualified=*/true)) {
4359  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4360  NewProto->getParamType(Idx) };
4361  Warnings.push_back(Warn);
4362  ArgTypes.push_back(NewParm->getType());
4363  } else
4364  LooseCompatible = false;
4365  }
4366 
4367  if (LooseCompatible) {
4368  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4369  Diag(Warnings[Warn].NewParm->getLocation(),
4370  diag::ext_param_promoted_not_compatible_with_prototype)
4371  << Warnings[Warn].PromotedType
4372  << Warnings[Warn].OldParm->getType();
4373  if (Warnings[Warn].OldParm->getLocation().isValid())
4374  Diag(Warnings[Warn].OldParm->getLocation(),
4375  diag::note_previous_declaration);
4376  }
4377 
4378  if (MergeTypeWithOld)
4379  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4380  OldProto->getExtProtoInfo()));
4381  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4382  }
4383 
4384  // Fall through to diagnose conflicting types.
4385  }
4386 
4387  // A function that has already been declared has been redeclared or
4388  // defined with a different type; show an appropriate diagnostic.
4389 
4390  // If the previous declaration was an implicitly-generated builtin
4391  // declaration, then at the very least we should use a specialized note.
4392  unsigned BuiltinID;
4393  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4394  // If it's actually a library-defined builtin function like 'malloc'
4395  // or 'printf', just warn about the incompatible redeclaration.
4396  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4397  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4398  Diag(OldLocation, diag::note_previous_builtin_declaration)
4399  << Old << Old->getType();
4400  return false;
4401  }
4402 
4403  PrevDiag = diag::note_previous_builtin_declaration;
4404  }
4405 
4406  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4407  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4408  return true;
4409 }
4410 
4411 /// Completes the merge of two function declarations that are
4412 /// known to be compatible.
4413 ///
4414 /// This routine handles the merging of attributes and other
4415 /// properties of function declarations from the old declaration to
4416 /// the new declaration, once we know that New is in fact a
4417 /// redeclaration of Old.
4418 ///
4419 /// \returns false
4421  Scope *S, bool MergeTypeWithOld) {
4422  // Merge the attributes
4423  mergeDeclAttributes(New, Old);
4424 
4425  // Merge "pure" flag.
4426  if (Old->isPureVirtual())
4427  New->setIsPureVirtual();
4428 
4429  // Merge "used" flag.
4430  if (Old->getMostRecentDecl()->isUsed(false))
4431  New->setIsUsed();
4432 
4433  // Merge attributes from the parameters. These can mismatch with K&R
4434  // declarations.
4435  if (New->getNumParams() == Old->getNumParams())
4436  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4437  ParmVarDecl *NewParam = New->getParamDecl(i);
4438  ParmVarDecl *OldParam = Old->getParamDecl(i);
4439  mergeParamDeclAttributes(NewParam, OldParam, *this);
4440  mergeParamDeclTypes(NewParam, OldParam, *this);
4441  }
4442 
4443  if (getLangOpts().CPlusPlus)
4444  return MergeCXXFunctionDecl(New, Old, S);
4445 
4446  // Merge the function types so the we get the composite types for the return
4447  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4448  // was visible.
4449  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4450  if (!Merged.isNull() && MergeTypeWithOld)
4451  New->setType(Merged);
4452 
4453  return false;
4454 }
4455 
4457  ObjCMethodDecl *oldMethod) {
4458  // Merge the attributes, including deprecated/unavailable
4459  AvailabilityMergeKind MergeKind =
4460  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4461  ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4462  : AMK_ProtocolImplementation)
4463  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4464  : AMK_Override;
4465 
4466  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4467 
4468  // Merge attributes from the parameters.
4470  oe = oldMethod->param_end();
4472  ni = newMethod->param_begin(), ne = newMethod->param_end();
4473  ni != ne && oi != oe; ++ni, ++oi)
4474  mergeParamDeclAttributes(*ni, *oi, *this);
4475 
4476  CheckObjCMethodOverride(newMethod, oldMethod);
4477 }
4478 
4479 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4480  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4481 
4483  ? diag::err_redefinition_different_type
4484  : diag::err_redeclaration_different_type)
4485  << New->getDeclName() << New->getType() << Old->getType();
4486 
4487  diag::kind PrevDiag;
4488  SourceLocation OldLocation;
4489  std::tie(PrevDiag, OldLocation)
4491  S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4492  New->setInvalidDecl();
4493 }
4494 
4495 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4496 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4497 /// emitting diagnostics as appropriate.
4498 ///
4499 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4500 /// to here in AddInitializerToDecl. We can't check them before the initializer
4501 /// is attached.
4503  bool MergeTypeWithOld) {
4504  if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4505  return;
4506 
4507  QualType MergedT;
4508  if (getLangOpts().CPlusPlus) {
4509  if (New->getType()->isUndeducedType()) {
4510  // We don't know what the new type is until the initializer is attached.
4511  return;
4512  } else if (Context.hasSameType(New->getType(), Old->getType())) {
4513  // These could still be something that needs exception specs checked.
4514  return MergeVarDeclExceptionSpecs(New, Old);
4515  }
4516  // C++ [basic.link]p10:
4517  // [...] the types specified by all declarations referring to a given
4518  // object or function shall be identical, except that declarations for an
4519  // array object can specify array types that differ by the presence or
4520  // absence of a major array bound (8.3.4).
4521  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4522  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4523  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4524 
4525  // We are merging a variable declaration New into Old. If it has an array
4526  // bound, and that bound differs from Old's bound, we should diagnose the
4527  // mismatch.
4528  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4529  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4530  PrevVD = PrevVD->getPreviousDecl()) {
4531  QualType PrevVDTy = PrevVD->getType();
4532  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4533  continue;
4534 
4535  if (!Context.hasSameType(New->getType(), PrevVDTy))
4536  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4537  }
4538  }
4539 
4540  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4541  if (Context.hasSameType(OldArray->getElementType(),
4542  NewArray->getElementType()))
4543  MergedT = New->getType();
4544  }
4545  // FIXME: Check visibility. New is hidden but has a complete type. If New
4546  // has no array bound, it should not inherit one from Old, if Old is not
4547  // visible.
4548  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4549  if (Context.hasSameType(OldArray->getElementType(),
4550  NewArray->getElementType()))
4551  MergedT = Old->getType();
4552  }
4553  }
4554  else if (New->getType()->isObjCObjectPointerType() &&
4555  Old->getType()->isObjCObjectPointerType()) {
4556  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4557  Old->getType());
4558  }
4559  } else {
4560  // C 6.2.7p2:
4561  // All declarations that refer to the same object or function shall have
4562  // compatible type.
4563  MergedT = Context.mergeTypes(New->getType(), Old->getType());
4564  }
4565  if (MergedT.isNull()) {
4566  // It's OK if we couldn't merge types if either type is dependent, for a
4567  // block-scope variable. In other cases (static data members of class
4568  // templates, variable templates, ...), we require the types to be
4569  // equivalent.
4570  // FIXME: The C++ standard doesn't say anything about this.
4571  if ((New->getType()->isDependentType() ||
4572  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4573  // If the old type was dependent, we can't merge with it, so the new type
4574  // becomes dependent for now. We'll reproduce the original type when we
4575  // instantiate the TypeSourceInfo for the variable.
4576  if (!New->getType()->isDependentType() && MergeTypeWithOld)
4577  New->setType(Context.DependentTy);
4578  return;
4579  }
4580  return diagnoseVarDeclTypeMismatch(*this, New, Old);
4581  }
4582 
4583  // Don't actually update the type on the new declaration if the old
4584  // declaration was an extern declaration in a different scope.
4585  if (MergeTypeWithOld)
4586  New->setType(MergedT);
4587 }
4588 
4589 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4591  // C11 6.2.7p4:
4592  // For an identifier with internal or external linkage declared
4593  // in a scope in which a prior declaration of that identifier is
4594  // visible, if the prior declaration specifies internal or
4595  // external linkage, the type of the identifier at the later
4596  // declaration becomes the composite type.
4597  //
4598  // If the variable isn't visible, we do not merge with its type.
4599  if (Previous.isShadowed())
4600  return false;
4601 
4602  if (S.getLangOpts().CPlusPlus) {
4603  // C++11 [dcl.array]p3:
4604  // If there is a preceding declaration of the entity in the same
4605  // scope in which the bound was specified, an omitted array bound
4606  // is taken to be the same as in that earlier declaration.
4607  return NewVD->isPreviousDeclInSameBlockScope() ||
4608  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4610  } else {
4611  // If the old declaration was function-local, don't merge with its
4612  // type unless we're in the same function.
4613  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4614  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4615  }
4616 }
4617 
4618 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4619 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4620 /// situation, merging decls or emitting diagnostics as appropriate.
4621 ///
4622 /// Tentative definition rules (C99 6.9.2p2) are checked by
4623 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4624 /// definitions here, since the initializer hasn't been attached.
4625 ///
4627  // If the new decl is already invalid, don't do any other checking.
4628  if (New->isInvalidDecl())
4629  return;
4630 
4631  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4632  return;
4633 
4634  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4635 
4636  // Verify the old decl was also a variable or variable template.
4637  VarDecl *Old = nullptr;
4638  VarTemplateDecl *OldTemplate = nullptr;
4639  if (Previous.isSingleResult()) {
4640  if (NewTemplate) {
4641  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4642  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4643 
4644  if (auto *Shadow =
4645  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4646  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4647  return New->setInvalidDecl();
4648  } else {
4649  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4650 
4651  if (auto *Shadow =
4652  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4653  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4654  return New->setInvalidDecl();
4655  }
4656  }
4657  if (!Old) {
4658  Diag(New->getLocation(), diag::err_redefinition_different_kind)
4659  << New->getDeclName();
4660  notePreviousDefinition(Previous.getRepresentativeDecl(),
4661  New->getLocation());
4662  return New->setInvalidDecl();
4663  }
4664 
4665  // If the old declaration was found in an inline namespace and the new
4666  // declaration was qualified, update the DeclContext to match.
4668 
4669  // Ensure the template parameters are compatible.
4670  if (NewTemplate &&
4671  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4672  OldTemplate->getTemplateParameters(),
4673  /*Complain=*/true, TPL_TemplateMatch))
4674  return New->setInvalidDecl();
4675 
4676  // C++ [class.mem]p1:
4677  // A member shall not be declared twice in the member-specification [...]
4678  //
4679  // Here, we need only consider static data members.
4680  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4681  Diag(New->getLocation(), diag::err_duplicate_member)
4682  << New->getIdentifier();
4683  Diag(Old->getLocation(), diag::note_previous_declaration);
4684  New->setInvalidDecl();
4685  }
4686 
4687  mergeDeclAttributes(New, Old);
4688  // Warn if an already-declared variable is made a weak_import in a subsequent
4689  // declaration
4690  if (New->hasAttr<WeakImportAttr>() &&
4691  Old->getStorageClass() == SC_None &&
4692  !Old->hasAttr<WeakImportAttr>()) {
4693  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4694  Diag(Old->getLocation(), diag::note_previous_declaration);
4695  // Remove weak_import attribute on new declaration.
4696  New->dropAttr<WeakImportAttr>();
4697  }
4698 
4699  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4700  if (!Old->hasAttr<InternalLinkageAttr>()) {
4701  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4702  << ILA;
4703  Diag(Old->getLocation(), diag::note_previous_declaration);
4704  New->dropAttr<InternalLinkageAttr>();
4705  }
4706 
4707  // Merge the types.
4708  VarDecl *MostRecent = Old->getMostRecentDecl();
4709  if (MostRecent != Old) {
4710  MergeVarDeclTypes(New, MostRecent,
4711  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4712  if (New->isInvalidDecl())
4713  return;
4714  }
4715 
4716  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4717  if (New->isInvalidDecl())
4718  return;
4719 
4720  diag::kind PrevDiag;
4721  SourceLocation OldLocation;
4722  std::tie(PrevDiag, OldLocation) =
4724 
4725  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4726  if (New->getStorageClass() == SC_Static &&
4727  !New->isStaticDataMember() &&
4728  Old->hasExternalFormalLinkage()) {
4729  if (getLangOpts().MicrosoftExt) {
4730  Diag(New->getLocation(), diag::ext_static_non_static)
4731  << New->getDeclName();
4732  Diag(OldLocation, PrevDiag);
4733  } else {
4734  Diag(New->getLocation(), diag::err_static_non_static)
4735  << New->getDeclName();
4736  Diag(OldLocation, PrevDiag);
4737  return New->setInvalidDecl();
4738  }
4739  }
4740  // C99 6.2.2p4:
4741  // For an identifier declared with the storage-class specifier
4742  // extern in a scope in which a prior declaration of that
4743  // identifier is visible,23) if the prior declaration specifies
4744  // internal or external linkage, the linkage of the identifier at
4745  // the later declaration is the same as the linkage specified at
4746  // the prior declaration. If no prior declaration is visible, or
4747  // if the prior declaration specifies no linkage, then the
4748  // identifier has external linkage.
4749  if (New->hasExternalStorage() && Old->hasLinkage())
4750  /* Okay */;
4751  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4752  !New->isStaticDataMember() &&
4754  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4755  Diag(OldLocation, PrevDiag);
4756  return New->setInvalidDecl();
4757  }
4758 
4759  // Check if extern is followed by non-extern and vice-versa.
4760  if (New->hasExternalStorage() &&
4761  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4762  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4763  Diag(OldLocation, PrevDiag);
4764  return New->setInvalidDecl();
4765  }
4766  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4767  !New->hasExternalStorage()) {
4768  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4769  Diag(OldLocation, PrevDiag);
4770  return New->setInvalidDecl();
4771  }
4772 
4773  if (CheckRedeclarationInModule(New, Old))
4774  return;
4775 
4776  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4777 
4778  // FIXME: The test for external storage here seems wrong? We still
4779  // need to check for mismatches.
4780  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4781  // Don't complain about out-of-line definitions of static members.
4782  !(Old->getLexicalDeclContext()->isRecord() &&
4783  !New->getLexicalDeclContext()->isRecord())) {
4784  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4785  Diag(OldLocation, PrevDiag);
4786  return New->setInvalidDecl();
4787  }
4788 
4789  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4790  if (VarDecl *Def = Old->getDefinition()) {
4791  // C++1z [dcl.fcn.spec]p4:
4792  // If the definition of a variable appears in a translation unit before
4793  // its first declaration as inline, the program is ill-formed.
4794  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4795  Diag(Def->getLocation(), diag::note_previous_definition);
4796  }
4797  }
4798 
4799  // If this redeclaration makes the variable inline, we may need to add it to
4800  // UndefinedButUsed.
4801  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4802  !Old->getDefinition() && !New->isThisDeclarationADefinition())
4803  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4804  SourceLocation()));
4805 
4806  if (New->getTLSKind() != Old->getTLSKind()) {
4807  if (!Old->getTLSKind()) {
4808  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4809  Diag(OldLocation, PrevDiag);
4810  } else if (!New->getTLSKind()) {
4811  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4812  Diag(OldLocation, PrevDiag);
4813  } else {
4814  // Do not allow redeclaration to change the variable between requiring
4815  // static and dynamic initialization.
4816  // FIXME: GCC allows this, but uses the TLS keyword on the first
4817  // declaration to determine the kind. Do we need to be compatible here?
4818  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4819  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4820  Diag(OldLocation, PrevDiag);
4821  }
4822  }
4823 
4824  // C++ doesn't have tentative definitions, so go right ahead and check here.
4825  if (getLangOpts().CPlusPlus) {
4826  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4827  Old->getCanonicalDecl()->isConstexpr()) {
4828  // This definition won't be a definition any more once it's been merged.
4829  Diag(New->getLocation(),
4830  diag::warn_deprecated_redundant_constexpr_static_def);
4831  } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4832  VarDecl *Def = Old->getDefinition();
4833  if (Def && checkVarDeclRedefinition(Def, New))
4834  return;
4835  }
4836  }
4837 
4838  if (haveIncompatibleLanguageLinkages(Old, New)) {
4839  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4840  Diag(OldLocation, PrevDiag);
4841  New->setInvalidDecl();
4842  return;
4843  }
4844 
4845  // Merge "used" flag.
4846  if (Old->getMostRecentDecl()->isUsed(false))
4847  New->setIsUsed();
4848 
4849  // Keep a chain of previous declarations.
4850  New->setPreviousDecl(Old);
4851  if (NewTemplate)
4852  NewTemplate->setPreviousDecl(OldTemplate);
4853 
4854  // Inherit access appropriately.
4855  New->setAccess(Old->getAccess());
4856  if (NewTemplate)
4857  NewTemplate->setAccess(New->getAccess());
4858 
4859  if (Old->isInline())
4860  New->setImplicitlyInline();
4861 }
4862 
4864  SourceManager &SrcMgr = getSourceManager();
4865  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4866  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4867  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4868  auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4869  auto &HSI = PP.getHeaderSearchInfo();
4870  StringRef HdrFilename =
4871  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4872 
4873  auto noteFromModuleOrInclude = [&](Module *Mod,
4874  SourceLocation IncLoc) -> bool {
4875  // Redefinition errors with modules are common with non modular mapped
4876  // headers, example: a non-modular header H in module A that also gets
4877  // included directly in a TU. Pointing twice to the same header/definition
4878  // is confusing, try to get better diagnostics when modules is on.
4879  if (IncLoc.isValid()) {
4880  if (Mod) {
4881  Diag(IncLoc, diag::note_redefinition_modules_same_file)
4882  << HdrFilename.str() << Mod->getFullModuleName();
4883  if (!Mod->DefinitionLoc.isInvalid())
4884  Diag(Mod->DefinitionLoc, diag::note_defined_here)
4885  << Mod->getFullModuleName();
4886  } else {
4887  Diag(IncLoc, diag::note_redefinition_include_same_file)
4888  << HdrFilename.str();
4889  }
4890  return true;
4891  }
4892 
4893  return false;
4894  };
4895 
4896  // Is it the same file and same offset? Provide more information on why
4897  // this leads to a redefinition error.
4898  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4899  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4900  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4901  bool EmittedDiag =
4902  noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4903  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4904 
4905  // If the header has no guards, emit a note suggesting one.
4906  if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4907  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4908 
4909  if (EmittedDiag)
4910  return;
4911  }
4912 
4913  // Redefinition coming from different files or couldn't do better above.
4914  if (Old->getLocation().isValid())
4915  Diag(Old->getLocation(), diag::note_previous_definition);
4916 }
4917 
4918 /// We've just determined that \p Old and \p New both appear to be definitions
4919 /// of the same variable. Either diagnose or fix the problem.
4921  if (!hasVisibleDefinition(Old) &&
4922  (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4923  isa<VarTemplateSpecializationDecl>(New) ||
4925  New->getDeclContext()->isDependentContext())) {
4926  // The previous definition is hidden, and multiple definitions are
4927  // permitted (in separate TUs). Demote this to a declaration.
4929 
4930  // Make the canonical definition visible.
4931  if (auto *OldTD = Old->getDescribedVarTemplate())
4932  makeMergedDefinitionVisible(OldTD);
4933  makeMergedDefinitionVisible(Old);
4934  return false;
4935  } else {
4936  Diag(New->getLocation(), diag::err_redefinition) << New;
4937  notePreviousDefinition(Old, New->getLocation());
4938  New->setInvalidDecl();
4939  return true;
4940  }
4941 }
4942 
4943 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4944 /// no declarator (e.g. "struct foo;") is parsed.
4946  DeclSpec &DS,
4947  const ParsedAttributesView &DeclAttrs,
4948  RecordDecl *&AnonRecord) {
4949  return ParsedFreeStandingDeclSpec(
4950  S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4951 }
4952 
4953 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4954 // disambiguate entities defined in different scopes.
4955 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4956 // compatibility.
4957 // We will pick our mangling number depending on which version of MSVC is being
4958 // targeted.
4959 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4961  ? S->getMSCurManglingNumber()
4962  : S->getMSLastManglingNumber();
4963 }
4964 
4965 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4966  if (!Context.getLangOpts().CPlusPlus)
4967  return;
4968 
4969  if (isa<CXXRecordDecl>(Tag->getParent())) {
4970  // If this tag is the direct child of a class, number it if
4971  // it is anonymous.
4972  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4973  return;
4974  MangleNumberingContext &MCtx =
4975  Context.getManglingNumberContext(Tag->getParent());
4976  Context.setManglingNumber(
4977  Tag, MCtx.getManglingNumber(
4978  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4979  return;
4980  }
4981 
4982  // If this tag isn't a direct child of a class, number it if it is local.
4983  MangleNumberingContext *MCtx;
4984  Decl *ManglingContextDecl;
4985  std::tie(MCtx, ManglingContextDecl) =
4986  getCurrentMangleNumberContext(Tag->getDeclContext());
4987  if (MCtx) {
4988  Context.setManglingNumber(
4989  Tag, MCtx->getManglingNumber(
4990  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4991  }
4992 }
4993 
4994 namespace {
4995 struct NonCLikeKind {
4996  enum {
4997  None,
4998  BaseClass,
4999  DefaultMemberInit,
5000  Lambda,
5001  Friend,
5002  OtherMember,
5003  Invalid,
5004  } Kind = None;
5005  SourceRange Range;
5006 
5007  explicit operator bool() { return Kind != None; }
5008 };
5009 }
5010 
5011 /// Determine whether a class is C-like, according to the rules of C++
5012 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
5013 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5014  if (RD->isInvalidDecl())
5015  return {NonCLikeKind::Invalid, {}};
5016 
5017  // C++ [dcl.typedef]p9: [P1766R1]
5018  // An unnamed class with a typedef name for linkage purposes shall not
5019  //
5020  // -- have any base classes
5021  if (RD->getNumBases())
5022  return {NonCLikeKind::BaseClass,
5024  RD->bases_end()[-1].getEndLoc())};
5025  bool Invalid = false;
5026  for (Decl *D : RD->decls()) {
5027  // Don't complain about things we already diagnosed.
5028  if (D->isInvalidDecl()) {
5029  Invalid = true;
5030  continue;
5031  }
5032 
5033  // -- have any [...] default member initializers
5034  if (auto *FD = dyn_cast<FieldDecl>(D)) {
5035  if (FD->hasInClassInitializer()) {
5036  auto *Init = FD->getInClassInitializer();
5037  return {NonCLikeKind::DefaultMemberInit,
5038  Init ? Init->getSourceRange() : D->getSourceRange()};
5039  }
5040  continue;
5041  }
5042 
5043  // FIXME: We don't allow friend declarations. This violates the wording of
5044  // P1766, but not the intent.
5045  if (isa<FriendDecl>(D))
5046  return {NonCLikeKind::Friend, D->getSourceRange()};
5047 
5048  // -- declare any members other than non-static data members, member
5049  // enumerations, or member classes,
5050  if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
5051  isa<EnumDecl>(D))
5052  continue;
5053  auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5054  if (!MemberRD) {
5055  if (D->isImplicit())
5056  continue;
5057  return {NonCLikeKind::OtherMember, D->getSourceRange()};
5058  }
5059 
5060  // -- contain a lambda-expression,
5061  if (MemberRD->isLambda())
5062  return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5063 
5064  // and all member classes shall also satisfy these requirements
5065  // (recursively).
5066  if (MemberRD->isThisDeclarationADefinition()) {
5067  if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5068  return Kind;
5069  }
5070  }
5071 
5072  return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5073 }
5074 
5076  TypedefNameDecl *NewTD) {
5077  if (TagFromDeclSpec->isInvalidDecl())
5078  return;
5079 
5080  // Do nothing if the tag already has a name for linkage purposes.
5081  if (TagFromDeclSpec->hasNameForLinkage())
5082  return;
5083 
5084  // A well-formed anonymous tag must always be a TUK_Definition.
5085  assert(TagFromDeclSpec->isThisDeclarationADefinition());
5086 
5087  // The type must match the tag exactly; no qualifiers allowed.
5088  if (!Context.hasSameType(NewTD->getUnderlyingType(),
5089  Context.getTagDeclType(TagFromDeclSpec))) {
5090  if (getLangOpts().CPlusPlus)
5091  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5092  return;
5093  }
5094 
5095  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5096  // An unnamed class with a typedef name for linkage purposes shall [be
5097  // C-like].
5098  //
5099  // FIXME: Also diagnose if we've already computed the linkage. That ideally
5100  // shouldn't happen, but there are constructs that the language rule doesn't
5101  // disallow for which we can't reasonably avoid computing linkage early.
5102  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5103  NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5104  : NonCLikeKind();
5105  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5106  if (NonCLike || ChangesLinkage) {
5107  if (NonCLike.Kind == NonCLikeKind::Invalid)
5108  return;
5109 
5110  unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5111  if (ChangesLinkage) {
5112  // If the linkage changes, we can't accept this as an extension.
5113  if (NonCLike.Kind == NonCLikeKind::None)
5114  DiagID = diag::err_typedef_changes_linkage;
5115  else
5116  DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5117  }
5118 
5119  SourceLocation FixitLoc =
5120  getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5121  llvm::SmallString<40> TextToInsert;
5122  TextToInsert += ' ';
5123  TextToInsert += NewTD->getIdentifier()->getName();
5124 
5125  Diag(FixitLoc, DiagID)
5126  << isa<TypeAliasDecl>(NewTD)
5127  << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5128  if (NonCLike.Kind != NonCLikeKind::None) {
5129  Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5130  << NonCLike.Kind - 1 << NonCLike.Range;
5131  }
5132  Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5133  << NewTD << isa<TypeAliasDecl>(NewTD);
5134 
5135  if (ChangesLinkage)
5136  return;
5137  }
5138 
5139  // Otherwise, set this as the anon-decl typedef for the tag.
5140  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5141 }
5142 
5143 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5145  switch (T) {
5146  case DeclSpec::TST_class:
5147  return 0;
5148  case DeclSpec::TST_struct:
5149  return 1;
5151  return 2;
5152  case DeclSpec::TST_union:
5153  return 3;
5154  case DeclSpec::TST_enum:
5155  if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5156  if (ED->isScopedUsingClassTag())
5157  return 5;
5158  if (ED->isScoped())
5159  return 6;
5160  }
5161  return 4;
5162  default:
5163  llvm_unreachable("unexpected type specifier");
5164  }
5165 }
5166 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5167 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5168 /// parameters to cope with template friend declarations.
5170  DeclSpec &DS,
5171  const ParsedAttributesView &DeclAttrs,
5172  MultiTemplateParamsArg TemplateParams,
5173  bool IsExplicitInstantiation,
5174  RecordDecl *&AnonRecord) {
5175  Decl *TagD = nullptr;
5176  TagDecl *Tag = nullptr;
5177  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5182  TagD = DS.getRepAsDecl();
5183 
5184  if (!TagD) // We probably had an error
5185  return nullptr;
5186 
5187  // Note that the above type specs guarantee that the
5188  // type rep is a Decl, whereas in many of the others
5189  // it's a Type.
5190  if (isa<TagDecl>(TagD))
5191  Tag = cast<TagDecl>(TagD);
5192  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5193  Tag = CTD->getTemplatedDecl();
5194  }
5195 
5196  if (Tag) {
5197  handleTagNumbering(Tag, S);
5198  Tag->setFreeStanding();
5199  if (Tag->isInvalidDecl())
5200  return Tag;
5201  }
5202 
5203  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5204  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5205  // or incomplete types shall not be restrict-qualified."
5206  if (TypeQuals & DeclSpec::TQ_restrict)
5207  Diag(DS.getRestrictSpecLoc(),
5208  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5209  << DS.getSourceRange();
5210  }
5211 
5212  if (DS.isInlineSpecified())
5213  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5214  << getLangOpts().CPlusPlus17;
5215 
5216  if (DS.hasConstexprSpecifier()) {
5217  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5218  // and definitions of functions and variables.
5219  // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5220  // the declaration of a function or function template
5221  if (Tag)
5222  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5224  << static_cast<int>(DS.getConstexprSpecifier());
5225  else if (getLangOpts().C23)
5226  Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5227  else
5228  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5229  << static_cast<int>(DS.getConstexprSpecifier());
5230  // Don't emit warnings after this error.
5231  return TagD;
5232  }
5233 
5234  DiagnoseFunctionSpecifiers(DS);
5235 
5236  if (DS.isFriendSpecified()) {
5237  // If we're dealing with a decl but not a TagDecl, assume that
5238  // whatever routines created it handled the friendship aspect.
5239  if (TagD && !Tag)
5240  return nullptr;
5241  return ActOnFriendTypeDecl(S, DS, TemplateParams);
5242  }
5243 
5244  // Track whether this decl-specifier declares anything.
5245  bool DeclaresAnything = true;
5246 
5247  // Handle anonymous struct definitions.
5248  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5249  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5251  if (getLangOpts().CPlusPlus ||
5252  Record->getDeclContext()->isRecord()) {
5253  // If CurContext is a DeclContext that can contain statements,
5254  // RecursiveASTVisitor won't visit the decls that
5255  // BuildAnonymousStructOrUnion() will put into CurContext.
5256  // Also store them here so that they can be part of the
5257  // DeclStmt that gets created in this case.
5258  // FIXME: Also return the IndirectFieldDecls created by
5259  // BuildAnonymousStructOr union, for the same reason?
5260  if (CurContext->isFunctionOrMethod())
5261  AnonRecord = Record;
5262  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5263  Context.getPrintingPolicy());
5264  }
5265 
5266  DeclaresAnything = false;
5267  }
5268  }
5269 
5270  // C11 6.7.2.1p2:
5271  // A struct-declaration that does not declare an anonymous structure or
5272  // anonymous union shall contain a struct-declarator-list.
5273  //
5274  // This rule also existed in C89 and C99; the grammar for struct-declaration
5275  // did not permit a struct-declaration without a struct-declarator-list.
5276  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5278  // Check for Microsoft C extension: anonymous struct/union member.
5279  // Handle 2 kinds of anonymous struct/union:
5280  // struct STRUCT;
5281  // union UNION;
5282  // and
5283  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5284  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5285  if ((Tag && Tag->getDeclName()) ||
5287  RecordDecl *Record = nullptr;
5288  if (Tag)
5289  Record = dyn_cast<RecordDecl>(Tag);
5290  else if (const RecordType *RT =
5292  Record = RT->getDecl();
5293  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5294  Record = UT->getDecl();
5295 
5296  if (Record && getLangOpts().MicrosoftExt) {
5297  Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5298  << Record->isUnion() << DS.getSourceRange();
5299  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5300  }
5301 
5302  DeclaresAnything = false;
5303  }
5304  }
5305 
5306  // Skip all the checks below if we have a type error.
5307  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5308  (TagD && TagD->isInvalidDecl()))
5309  return TagD;
5310 
5311  if (getLangOpts().CPlusPlus &&
5313  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5314  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5315  !Enum->getIdentifier() && !Enum->isInvalidDecl())
5316  DeclaresAnything = false;
5317 
5318  if (!DS.isMissingDeclaratorOk()) {
5319  // Customize diagnostic for a typedef missing a name.
5321  Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5322  << DS.getSourceRange();
5323  else
5324  DeclaresAnything = false;
5325  }
5326 
5327  if (DS.isModulePrivateSpecified() &&
5328  Tag && Tag->getDeclContext()->isFunctionOrMethod())
5329  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5330  << llvm::to_underlying(Tag->getTagKind())
5332 
5333  ActOnDocumentableDecl(TagD);
5334 
5335  // C 6.7/2:
5336  // A declaration [...] shall declare at least a declarator [...], a tag,
5337  // or the members of an enumeration.
5338  // C++ [dcl.dcl]p3:
5339  // [If there are no declarators], and except for the declaration of an
5340  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5341  // names into the program, or shall redeclare a name introduced by a
5342  // previous declaration.
5343  if (!DeclaresAnything) {
5344  // In C, we allow this as a (popular) extension / bug. Don't bother
5345  // producing further diagnostics for redundant qualifiers after this.
5346  Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5347  ? diag::err_no_declarators
5348  : diag::ext_no_declarators)
5349  << DS.getSourceRange();
5350  return TagD;
5351  }
5352 
5353  // C++ [dcl.stc]p1:
5354  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5355  // init-declarator-list of the declaration shall not be empty.
5356  // C++ [dcl.fct.spec]p1:
5357  // If a cv-qualifier appears in a decl-specifier-seq, the
5358  // init-declarator-list of the declaration shall not be empty.
5359  //
5360  // Spurious qualifiers here appear to be valid in C.
5361  unsigned DiagID = diag::warn_standalone_specifier;
5362  if (getLangOpts().CPlusPlus)
5363  DiagID = diag::ext_standalone_specifier;
5364 
5365  // Note that a linkage-specification sets a storage class, but
5366  // 'extern "C" struct foo;' is actually valid and not theoretically
5367  // useless.
5368  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5369  if (SCS == DeclSpec::SCS_mutable)
5370  // Since mutable is not a viable storage class specifier in C, there is
5371  // no reason to treat it as an extension. Instead, diagnose as an error.
5372  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5373  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5374  Diag(DS.getStorageClassSpecLoc(), DiagID)
5376  }
5377 
5378  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5379  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5380  << DeclSpec::getSpecifierName(TSCS);
5381  if (DS.getTypeQualifiers()) {
5383  Diag(DS.getConstSpecLoc(), DiagID) << "const";
5385  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5386  // Restrict is covered above.
5388  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5390  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5391  }
5392 
5393  // Warn about ignored type attributes, for example:
5394  // __attribute__((aligned)) struct A;
5395  // Attributes should be placed after tag to apply to type declaration.
5396  if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5397  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5398  if (TypeSpecType == DeclSpec::TST_class ||
5399  TypeSpecType == DeclSpec::TST_struct ||
5400  TypeSpecType == DeclSpec::TST_interface ||
5401  TypeSpecType == DeclSpec::TST_union ||
5402  TypeSpecType == DeclSpec::TST_enum) {
5403 
5404  auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5405  unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5406  if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5407  DiagnosticId = diag::warn_attribute_ignored;
5408  else if (AL.isRegularKeywordAttribute())
5409  DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5410  else
5411  DiagnosticId = diag::warn_declspec_attribute_ignored;
5412  Diag(AL.getLoc(), DiagnosticId)
5413  << AL << GetDiagnosticTypeSpecifierID(DS);
5414  };
5415 
5416  llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5417  llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5418  }
5419  }
5420 
5421  return TagD;
5422 }
5423 
5424 /// We are trying to inject an anonymous member into the given scope;
5425 /// check if there's an existing declaration that can't be overloaded.
5426 ///
5427 /// \return true if this is a forbidden redeclaration
5428 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5429  DeclContext *Owner,
5430  DeclarationName Name,
5431  SourceLocation NameLoc, bool IsUnion,
5432  StorageClass SC) {
5433  LookupResult R(SemaRef, Name, NameLoc,
5434  Owner->isRecord() ? Sema::LookupMemberName
5437  if (!SemaRef.LookupName(R, S)) return false;
5438 
5439  // Pick a representative declaration.
5441  assert(PrevDecl && "Expected a non-null Decl");
5442 
5443  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5444  return false;
5445 
5446  if (SC == StorageClass::SC_None &&
5447  PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5448  (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5449  if (!Owner->isRecord())
5450  SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5451  return false;
5452  }
5453 
5454  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5455  << IsUnion << Name;
5456  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5457 
5458  return true;
5459 }
5460 
5462  if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5463  DiagPlaceholderFieldDeclDefinitions(RD);
5464 }
5465 
5466 /// Emit diagnostic warnings for placeholder members.
5467 /// We can only do that after the class is fully constructed,
5468 /// as anonymous union/structs can insert placeholders
5469 /// in their parent scope (which might be a Record).
5471  if (!getLangOpts().CPlusPlus)
5472  return;
5473 
5474  // This function can be parsed before we have validated the
5475  // structure as an anonymous struct
5476  if (Record->isAnonymousStructOrUnion())
5477  return;
5478 
5479  const NamedDecl *First = 0;
5480  for (const Decl *D : Record->decls()) {
5481  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5482  if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5483  continue;
5484  if (!First)
5485  First = ND;
5486  else
5487  DiagPlaceholderVariableDefinition(ND->getLocation());
5488  }
5489 }
5490 
5491 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5492 /// anonymous struct or union AnonRecord into the owning context Owner
5493 /// and scope S. This routine will be invoked just after we realize
5494 /// that an unnamed union or struct is actually an anonymous union or
5495 /// struct, e.g.,
5496 ///
5497 /// @code
5498 /// union {
5499 /// int i;
5500 /// float f;
5501 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5502 /// // f into the surrounding scope.x
5503 /// @endcode
5504 ///
5505 /// This routine is recursive, injecting the names of nested anonymous
5506 /// structs/unions into the owning context and scope as well.
5507 static bool
5509  RecordDecl *AnonRecord, AccessSpecifier AS,
5510  StorageClass SC,
5511  SmallVectorImpl<NamedDecl *> &Chaining) {
5512  bool Invalid = false;
5513 
5514  // Look every FieldDecl and IndirectFieldDecl with a name.
5515  for (auto *D : AnonRecord->decls()) {
5516  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5517  cast<NamedDecl>(D)->getDeclName()) {
5518  ValueDecl *VD = cast<ValueDecl>(D);
5519  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5520  VD->getLocation(), AnonRecord->isUnion(),
5521  SC)) {
5522  // C++ [class.union]p2:
5523  // The names of the members of an anonymous union shall be
5524  // distinct from the names of any other entity in the
5525  // scope in which the anonymous union is declared.
5526  Invalid = true;
5527  } else {
5528  // C++ [class.union]p2:
5529  // For the purpose of name lookup, after the anonymous union
5530  // definition, the members of the anonymous union are
5531  // considered to have been defined in the scope in which the
5532  // anonymous union is declared.
5533  unsigned OldChainingSize = Chaining.size();
5534  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5535  Chaining.append(IF->chain_begin(), IF->chain_end());
5536  else
5537  Chaining.push_back(VD);
5538 
5539  assert(Chaining.size() >= 2);
5540  NamedDecl **NamedChain =
5541  new (SemaRef.Context)NamedDecl*[Chaining.size()];
5542  for (unsigned i = 0; i < Chaining.size(); i++)
5543  NamedChain[i] = Chaining[i];
5544 
5546  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5547  VD->getType(), {NamedChain, Chaining.size()});
5548 
5549  for (const auto *Attr : VD->attrs())
5550  IndirectField->addAttr(Attr->clone(SemaRef.Context));
5551 
5552  IndirectField->setAccess(AS);
5553  IndirectField->setImplicit();
5554  SemaRef.PushOnScopeChains(IndirectField, S);
5555 
5556  // That includes picking up the appropriate access specifier.
5557  if (AS != AS_none) IndirectField->setAccess(AS);
5558 
5559  Chaining.resize(OldChainingSize);
5560  }
5561  }
5562  }
5563 
5564  return Invalid;
5565 }
5566 
5567 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5568 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5569 /// illegal input values are mapped to SC_None.
5570 static StorageClass
5572  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5573  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5574  "Parser allowed 'typedef' as storage class VarDecl.");
5575  switch (StorageClassSpec) {
5576  case DeclSpec::SCS_unspecified: return SC_None;
5577  case DeclSpec::SCS_extern:
5578  if (DS.isExternInLinkageSpec())
5579  return SC_None;
5580  return SC_Extern;
5581  case DeclSpec::SCS_static: return SC_Static;
5582  case DeclSpec::SCS_auto: return SC_Auto;
5583  case DeclSpec::SCS_register: return SC_Register;
5585  // Illegal SCSs map to None: error reporting is up to the caller.
5586  case DeclSpec::SCS_mutable: // Fall through.
5587  case DeclSpec::SCS_typedef: return SC_None;
5588  }
5589  llvm_unreachable("unknown storage class specifier");
5590 }
5591 
5593  assert(Record->hasInClassInitializer());
5594 
5595  for (const auto *I : Record->decls()) {
5596  const auto *FD = dyn_cast<FieldDecl>(I);
5597  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5598  FD = IFD->getAnonField();
5599  if (FD && FD->hasInClassInitializer())
5600  return FD->getLocation();
5601  }
5602 
5603  llvm_unreachable("couldn't find in-class initializer");
5604 }
5605 
5607  SourceLocation DefaultInitLoc) {
5608  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5609  return;
5610 
5611  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5612  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5613 }
5614 
5616  CXXRecordDecl *AnonUnion) {
5617  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5618  return;
5619 
5621 }
5622 
5623 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5624 /// anonymous structure or union. Anonymous unions are a C++ feature
5625 /// (C++ [class.union]) and a C11 feature; anonymous structures
5626 /// are a C11 feature and GNU C++ extension.
5628  AccessSpecifier AS,
5629  RecordDecl *Record,
5630  const PrintingPolicy &Policy) {
5631  DeclContext *Owner = Record->getDeclContext();
5632 
5633  // Diagnose whether this anonymous struct/union is an extension.
5634  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5635  Diag(Record->getLocation(), diag::ext_anonymous_union);
5636  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5637  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5638  else if (!Record->isUnion() && !getLangOpts().C11)
5639  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5640 
5641  // C and C++ require different kinds of checks for anonymous
5642  // structs/unions.
5643  bool Invalid = false;
5644  if (getLangOpts().CPlusPlus) {
5645  const char *PrevSpec = nullptr;
5646  if (Record->isUnion()) {
5647  // C++ [class.union]p6:
5648  // C++17 [class.union.anon]p2:
5649  // Anonymous unions declared in a named namespace or in the
5650  // global namespace shall be declared static.
5651  unsigned DiagID;
5652  DeclContext *OwnerScope = Owner->getRedeclContext();
5654  (OwnerScope->isTranslationUnit() ||
5655  (OwnerScope->isNamespace() &&
5656  !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5657  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5658  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5659 
5660  // Recover by adding 'static'.
5662  PrevSpec, DiagID, Policy);
5663  }
5664  // C++ [class.union]p6:
5665  // A storage class is not allowed in a declaration of an
5666  // anonymous union in a class scope.
5668  isa<RecordDecl>(Owner)) {
5670  diag::err_anonymous_union_with_storage_spec)
5672 
5673  // Recover by removing the storage specifier.
5675  SourceLocation(),
5676  PrevSpec, DiagID, Context.getPrintingPolicy());
5677  }
5678  }
5679 
5680  // Ignore const/volatile/restrict qualifiers.
5681  if (DS.getTypeQualifiers()) {
5683  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5684  << Record->isUnion() << "const"
5687  Diag(DS.getVolatileSpecLoc(),
5688  diag::ext_anonymous_struct_union_qualified)
5689  << Record->isUnion() << "volatile"
5692  Diag(DS.getRestrictSpecLoc(),
5693  diag::ext_anonymous_struct_union_qualified)
5694  << Record->isUnion() << "restrict"
5697  Diag(DS.getAtomicSpecLoc(),
5698  diag::ext_anonymous_struct_union_qualified)
5699  << Record->isUnion() << "_Atomic"
5703  diag::ext_anonymous_struct_union_qualified)
5704  << Record->isUnion() << "__unaligned"
5706 
5707  DS.ClearTypeQualifiers();
5708  }
5709 
5710  // C++ [class.union]p2:
5711  // The member-specification of an anonymous union shall only
5712  // define non-static data members. [Note: nested types and
5713  // functions cannot be declared within an anonymous union. ]
5714  for (auto *Mem : Record->decls()) {
5715  // Ignore invalid declarations; we already diagnosed them.
5716  if (Mem->isInvalidDecl())
5717  continue;
5718 
5719  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5720  // C++ [class.union]p3:
5721  // An anonymous union shall not have private or protected
5722  // members (clause 11).
5723  assert(FD->getAccess() != AS_none);
5724  if (FD->getAccess() != AS_public) {
5725  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5726  << Record->isUnion() << (FD->getAccess() == AS_protected);
5727  Invalid = true;
5728  }
5729 
5730  // C++ [class.union]p1
5731  // An object of a class with a non-trivial constructor, a non-trivial
5732  // copy constructor, a non-trivial destructor, or a non-trivial copy
5733  // assignment operator cannot be a member of a union, nor can an
5734  // array of such objects.
5735  if (CheckNontrivialField(FD))
5736  Invalid = true;
5737  } else if (Mem->isImplicit()) {
5738  // Any implicit members are fine.
5739  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5740  // This is a type that showed up in an
5741  // elaborated-type-specifier inside the anonymous struct or
5742  // union, but which actually declares a type outside of the
5743  // anonymous struct or union. It's okay.
5744  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5745  if (!MemRecord->isAnonymousStructOrUnion() &&
5746  MemRecord->getDeclName()) {
5747  // Visual C++ allows type definition in anonymous struct or union.
5748  if (getLangOpts().MicrosoftExt)
5749  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5750  << Record->isUnion();
5751  else {
5752  // This is a nested type declaration.
5753  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5754  << Record->isUnion();
5755  Invalid = true;
5756  }
5757  } else {
5758  // This is an anonymous type definition within another anonymous type.
5759  // This is a popular extension, provided by Plan9, MSVC and GCC, but
5760  // not part of standard C++.
5761  Diag(MemRecord->getLocation(),
5762  diag::ext_anonymous_record_with_anonymous_type)
5763  << Record->isUnion();
5764  }
5765  } else if (isa<AccessSpecDecl>(Mem)) {
5766  // Any access specifier is fine.
5767  } else if (isa<StaticAssertDecl>(Mem)) {
5768  // In C++1z, static_assert declarations are also fine.
5769  } else {
5770  // We have something that isn't a non-static data
5771  // member. Complain about it.
5772  unsigned DK = diag::err_anonymous_record_bad_member;
5773  if (isa<TypeDecl>(Mem))
5774  DK = diag::err_anonymous_record_with_type;
5775  else if (isa<FunctionDecl>(Mem))
5776  DK = diag::err_anonymous_record_with_function;
5777  else if (isa<VarDecl>(Mem))
5778  DK = diag::err_anonymous_record_with_static;
5779 
5780  // Visual C++ allows type definition in anonymous struct or union.
5781  if (getLangOpts().MicrosoftExt &&
5782  DK == diag::err_anonymous_record_with_type)
5783  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5784  << Record->isUnion();
5785  else {
5786  Diag(Mem->getLocation(), DK) << Record->isUnion();
5787  Invalid = true;
5788  }
5789  }
5790  }
5791 
5792  // C++11 [class.union]p8 (DR1460):
5793  // At most one variant member of a union may have a
5794  // brace-or-equal-initializer.
5795  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5796  Owner->isRecord())
5797  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5798  cast<CXXRecordDecl>(Record));
5799  }
5800 
5801  if (!Record->isUnion() && !Owner->isRecord()) {
5802  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5803  << getLangOpts().CPlusPlus;
5804  Invalid = true;
5805  }
5806 
5807  // C++ [dcl.dcl]p3:
5808  // [If there are no declarators], and except for the declaration of an
5809  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5810  // names into the program
5811  // C++ [class.mem]p2:
5812  // each such member-declaration shall either declare at least one member
5813  // name of the class or declare at least one unnamed bit-field
5814  //
5815  // For C this is an error even for a named struct, and is diagnosed elsewhere.
5816  if (getLangOpts().CPlusPlus && Record->field_empty())
5817  Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5818 
5819  // Mock up a declarator.
5822  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5823  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5824 
5825  // Create a declaration for this anonymous struct/union.
5826  NamedDecl *Anon = nullptr;
5827  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5828  Anon = FieldDecl::Create(
5829  Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5830  /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5831  /*BitWidth=*/nullptr, /*Mutable=*/false,
5832  /*InitStyle=*/ICIS_NoInit);
5833  Anon->setAccess(AS);
5834  ProcessDeclAttributes(S, Anon, Dc);
5835 
5836  if (getLangOpts().CPlusPlus)
5837  FieldCollector->Add(cast<FieldDecl>(Anon));
5838  } else {
5839  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5840  if (SCSpec == DeclSpec::SCS_mutable) {
5841  // mutable can only appear on non-static class members, so it's always
5842  // an error here
5843  Diag(Record->getLocation(), diag::err_mutable_nonmember);
5844  Invalid = true;
5845  SC = SC_None;
5846  }
5847 
5848  Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5849  Record->getLocation(), /*IdentifierInfo=*/nullptr,
5850  Context.getTypeDeclType(Record), TInfo, SC);
5851  ProcessDeclAttributes(S, Anon, Dc);
5852 
5853  // Default-initialize the implicit variable. This initialization will be
5854  // trivial in almost all cases, except if a union member has an in-class
5855  // initializer:
5856  // union { int n = 0; };
5857  ActOnUninitializedDecl(Anon);
5858  }
5859  Anon->setImplicit();
5860 
5861  // Mark this as an anonymous struct/union type.
5862  Record->setAnonymousStructOrUnion(true);
5863 
5864  // Add the anonymous struct/union object to the current
5865  // context. We'll be referencing this object when we refer to one of
5866  // its members.
5867  Owner->addDecl(Anon);
5868 
5869  // Inject the members of the anonymous struct/union into the owning
5870  // context and into the identifier resolver chain for name lookup
5871  // purposes.
5873  Chain.push_back(Anon);
5874 
5875  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5876  Chain))
5877  Invalid = true;
5878 
5879  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5880  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5881  MangleNumberingContext *MCtx;
5882  Decl *ManglingContextDecl;
5883  std::tie(MCtx, ManglingContextDecl) =
5884  getCurrentMangleNumberContext(NewVD->getDeclContext());
5885  if (MCtx) {
5886  Context.setManglingNumber(
5887  NewVD, MCtx->getManglingNumber(
5888  NewVD, getMSManglingNumber(getLangOpts(), S)));
5889  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5890  }
5891  }
5892  }
5893 
5894  if (Invalid)
5895  Anon->setInvalidDecl();
5896 
5897  return Anon;
5898 }
5899 
5900 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5901 /// Microsoft C anonymous structure.
5902 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5903 /// Example:
5904 ///
5905 /// struct A { int a; };
5906 /// struct B { struct A; int b; };
5907 ///
5908 /// void foo() {
5909 /// B var;
5910 /// var.a = 3;
5911 /// }
5912 ///
5914  RecordDecl *Record) {
5915  assert(Record && "expected a record!");
5916 
5917  // Mock up a declarator.
5919  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5920  assert(TInfo && "couldn't build declarator info for anonymous struct");
5921 
5922  auto *ParentDecl = cast<RecordDecl>(CurContext);
5923  QualType RecTy = Context.getTypeDeclType(Record);
5924 
5925  // Create a declaration for this anonymous struct.
5926  NamedDecl *Anon =
5927  FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5928  /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5929  /*BitWidth=*/nullptr, /*Mutable=*/false,
5930  /*InitStyle=*/ICIS_NoInit);
5931  Anon->setImplicit();
5932 
5933  // Add the anonymous struct object to the current context.
5934  CurContext->addDecl(Anon);
5935 
5936  // Inject the members of the anonymous struct into the current
5937  // context and into the identifier resolver chain for name lookup
5938  // purposes.
5940  Chain.push_back(Anon);
5941 
5942  RecordDecl *RecordDef = Record->getDefinition();
5943  if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5944  diag::err_field_incomplete_or_sizeless) ||
5946  *this, S, CurContext, RecordDef, AS_none,
5948  Anon->setInvalidDecl();
5949  ParentDecl->setInvalidDecl();
5950  }
5951 
5952  return Anon;
5953 }
5954 
5955 /// GetNameForDeclarator - Determine the full declaration name for the
5956 /// given Declarator.
5958  return GetNameFromUnqualifiedId(D.getName());
5959 }
5960 
5961 /// Retrieves the declaration name from a parsed unqualified-id.
5964  DeclarationNameInfo NameInfo;
5965  NameInfo.setLoc(Name.StartLocation);
5966 
5967  switch (Name.getKind()) {
5968 
5971  NameInfo.setName(Name.Identifier);
5972  return NameInfo;
5973 
5975  // C++ [temp.deduct.guide]p3:
5976  // The simple-template-id shall name a class template specialization.
5977  // The template-name shall be the same identifier as the template-name
5978  // of the simple-template-id.
5979  // These together intend to imply that the template-name shall name a
5980  // class template.
5981  // FIXME: template<typename T> struct X {};
5982  // template<typename T> using Y = X<T>;
5983  // Y(int) -> Y<int>;
5984  // satisfies these rules but does not name a class template.
5985  TemplateName TN = Name.TemplateName.get().get();
5986  auto *Template = TN.getAsTemplateDecl();
5987  if (!Template || !isa<ClassTemplateDecl>(Template)) {
5988  Diag(Name.StartLocation,
5989  diag::err_deduction_guide_name_not_class_template)
5990  << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5991  if (Template)
5992  NoteTemplateLocation(*Template);
5993  return DeclarationNameInfo();
5994  }
5995 
5996  NameInfo.setName(
5997  Context.DeclarationNames.getCXXDeductionGuideName(Template));
5998  return NameInfo;
5999  }
6000 
6002  NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6003  Name.OperatorFunctionId.Operator));
6005  Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6006  return NameInfo;
6007 
6010  Name.Identifier));
6011  NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6012  return NameInfo;
6013 
6015  TypeSourceInfo *TInfo;
6016  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
6017  if (Ty.isNull())
6018  return DeclarationNameInfo();
6020  Context.getCanonicalType(Ty)));
6021  NameInfo.setNamedTypeInfo(TInfo);
6022  return NameInfo;
6023  }
6024 
6026  TypeSourceInfo *TInfo;
6027  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6028  if (Ty.isNull())
6029  return DeclarationNameInfo();
6031  Context.getCanonicalType(Ty)));
6032  NameInfo.setNamedTypeInfo(TInfo);
6033  return NameInfo;
6034  }
6035 
6037  // In well-formed code, we can only have a constructor
6038  // template-id that refers to the current context, so go there
6039  // to find the actual type being constructed.
6040  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6041  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6042  return DeclarationNameInfo();
6043 
6044  // Determine the type of the class being constructed.
6045  QualType CurClassType = Context.getTypeDeclType(CurClass);
6046 
6047  // FIXME: Check two things: that the template-id names the same type as
6048  // CurClassType, and that the template-id does not occur when the name
6049  // was qualified.
6050 
6052  Context.getCanonicalType(CurClassType)));
6053  // FIXME: should we retrieve TypeSourceInfo?
6054  NameInfo.setNamedTypeInfo(nullptr);
6055  return NameInfo;
6056  }
6057 
6059  TypeSourceInfo *TInfo;
6060  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6061  if (Ty.isNull())
6062  return DeclarationNameInfo();
6064  Context.getCanonicalType(Ty)));
6065  NameInfo.setNamedTypeInfo(TInfo);
6066  return NameInfo;
6067  }
6068 
6070  TemplateName TName = Name.TemplateId->Template.get();
6071  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6072  return Context.getNameForTemplate(TName, TNameLoc);
6073  }
6074 
6075  } // switch (Name.getKind())
6076 
6077  llvm_unreachable("Unknown name kind");
6078 }
6079 
6081  do {
6082  if (Ty->isPointerType() || Ty->isReferenceType())
6083  Ty = Ty->getPointeeType();
6084  else if (Ty->isArrayType())
6085  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6086  else
6087  return Ty.withoutLocalFastQualifiers();
6088  } while (true);
6089 }
6090 
6091 /// hasSimilarParameters - Determine whether the C++ functions Declaration
6092 /// and Definition have "nearly" matching parameters. This heuristic is
6093 /// used to improve diagnostics in the case where an out-of-line function
6094 /// definition doesn't match any declaration within the class or namespace.
6095 /// Also sets Params to the list of indices to the parameters that differ
6096 /// between the declaration and the definition. If hasSimilarParameters
6097 /// returns true and Params is empty, then all of the parameters match.
6098 static bool hasSimilarParameters(ASTContext &Context,
6099  FunctionDecl *Declaration,
6100  FunctionDecl *Definition,
6101  SmallVectorImpl<unsigned> &Params) {
6102  Params.clear();
6103  if (Declaration->param_size() != Definition->param_size())
6104  return false;
6105  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6106  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6107  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6108 
6109  // The parameter types are identical
6110  if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6111  continue;
6112 
6113  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6114  QualType DefParamBaseTy = getCoreType(DefParamTy);
6115  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6116  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6117 
6118  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6119  (DeclTyName && DeclTyName == DefTyName))
6120  Params.push_back(Idx);
6121  else // The two parameters aren't even close
6122  return false;
6123  }
6124 
6125  return true;
6126 }
6127 
6128 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6129 /// declarator needs to be rebuilt in the current instantiation.
6130 /// Any bits of declarator which appear before the name are valid for
6131 /// consideration here. That's specifically the type in the decl spec
6132 /// and the base type in any member-pointer chunks.
6134  DeclarationName Name) {
6135  // The types we specifically need to rebuild are:
6136  // - typenames, typeofs, and decltypes
6137  // - types which will become injected class names
6138  // Of course, we also need to rebuild any type referencing such a
6139  // type. It's safest to just say "dependent", but we call out a
6140  // few cases here.
6141 
6142  DeclSpec &DS = D.getMutableDeclSpec();
6143  switch (DS.getTypeSpecType()) {
6147 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6148 #include "clang/Basic/TransformTypeTraits.def"
6149  case DeclSpec::TST_atomic: {
6150  // Grab the type from the parser.
6151  TypeSourceInfo *TSI = nullptr;
6152  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6153  if (T.isNull() || !T->isInstantiationDependentType()) break;
6154 
6155  // Make sure there's a type source info. This isn't really much
6156  // of a waste; most dependent types should have type source info
6157  // attached already.
6158  if (!TSI)
6160 
6161  // Rebuild the type in the current instantiation.
6162  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6163  if (!TSI) return true;
6164 
6165  // Store the new type back in the decl spec.
6166  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6167  DS.UpdateTypeRep(LocType);
6168  break;
6169  }
6170 
6173  case DeclSpec::TST_typeofExpr: {
6174  Expr *E = DS.getRepAsExpr();
6176  if (Result.isInvalid()) return true;
6177  DS.UpdateExprRep(Result.get());
6178  break;
6179  }
6180 
6181  default:
6182  // Nothing to do for these decl specs.
6183  break;
6184  }
6185 
6186  // It doesn't matter what order we do this in.
6187  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6188  DeclaratorChunk &Chunk = D.getTypeObject(I);
6189 
6190  // The only type information in the declarator which can come
6191  // before the declaration name is the base type of a member
6192  // pointer.
6193  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6194  continue;
6195 
6196  // Rebuild the scope specifier in-place.
6197  CXXScopeSpec &SS = Chunk.Mem.Scope();
6199  return true;
6200  }
6201 
6202  return false;
6203 }
6204 
6205 /// Returns true if the declaration is declared in a system header or from a
6206 /// system macro.
6207 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6208  return SM.isInSystemHeader(D->getLocation()) ||
6209  SM.isInSystemMacro(D->getLocation());
6210 }
6211 
6213  // Avoid warning twice on the same identifier, and don't warn on redeclaration
6214  // of system decl.
6215  if (D->getPreviousDecl() || D->isImplicit())
6216  return;
6217  ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6218  if (Status != ReservedIdentifierStatus::NotReserved &&
6219  !isFromSystemHeader(Context.getSourceManager(), D)) {
6220  Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6221  << D << static_cast<int>(Status);
6222  }
6223 }
6224 
6227 
6228  // Check if we are in an `omp begin/end declare variant` scope. Handle this
6229  // declaration only if the `bind_to_declaration` extension is set.
6231  if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6232  if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6233  llvm::omp::TraitProperty::
6234  implementation_extension_bind_to_declaration))
6235  OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6236  S, D, MultiTemplateParamsArg(), Bases);
6237 
6238  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6239 
6240  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6241  Dcl && Dcl->getDeclContext()->isFileContext())
6243 
6244  if (!Bases.empty())
6245  OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
6246  Bases);
6247 
6248  return Dcl;
6249 }
6250 
6251 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6252 /// If T is the name of a class, then each of the following shall have a
6253 /// name different from T:
6254 /// - every static data member of class T;
6255 /// - every member function of class T
6256 /// - every member of class T that is itself a type;
6257 /// \returns true if the declaration name violates these rules.
6259  DeclarationNameInfo NameInfo) {
6260  DeclarationName Name = NameInfo.getName();
6261 
6262  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6263  while (Record && Record->isAnonymousStructOrUnion())
6264  Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6265  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6266  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6267  return true;
6268  }
6269 
6270  return false;
6271 }
6272 
6273 /// Diagnose a declaration whose declarator-id has the given
6274 /// nested-name-specifier.
6275 ///
6276 /// \param SS The nested-name-specifier of the declarator-id.
6277 ///
6278 /// \param DC The declaration context to which the nested-name-specifier
6279 /// resolves.
6280 ///
6281 /// \param Name The name of the entity being declared.
6282 ///
6283 /// \param Loc The location of the name of the entity being declared.
6284 ///
6285 /// \param IsMemberSpecialization Whether we are declaring a member
6286 /// specialization.
6287 ///
6288 /// \param TemplateId The template-id, if any.
6289 ///
6290 /// \returns true if we cannot safely recover from this error, false otherwise.
6292  DeclarationName Name,
6293  SourceLocation Loc,
6294  TemplateIdAnnotation *TemplateId,
6295  bool IsMemberSpecialization) {
6296  assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6297  "without nested-name-specifier");
6298  DeclContext *Cur = CurContext;
6299  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6300  Cur = Cur->getParent();
6301 
6302  // If the user provided a superfluous scope specifier that refers back to the
6303  // class in which the entity is already declared, diagnose and ignore it.
6304  //
6305  // class X {
6306  // void X::f();
6307  // };
6308  //
6309  // Note, it was once ill-formed to give redundant qualification in all
6310  // contexts, but that rule was removed by DR482.
6311  if (Cur->Equals(DC)) {
6312  if (Cur->isRecord()) {
6313  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6314  : diag::err_member_extra_qualification)
6315  << Name << FixItHint::CreateRemoval(SS.getRange());
6316  SS.clear();
6317  } else {
6318  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6319  }
6320  return false;
6321  }
6322 
6323  // Check whether the qualifying scope encloses the scope of the original
6324  // declaration. For a template-id, we perform the checks in
6325  // CheckTemplateSpecializationScope.
6326  if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6327  if (Cur->isRecord())
6328  Diag(Loc, diag::err_member_qualification)
6329  << Name << SS.getRange();
6330  else if (isa<TranslationUnitDecl>(DC))
6331  Diag(Loc, diag::err_invalid_declarator_global_scope)
6332  << Name << SS.getRange();
6333  else if (isa<FunctionDecl>(Cur))
6334  Diag(Loc, diag::err_invalid_declarator_in_function)
6335  << Name << SS.getRange();
6336  else if (isa<BlockDecl>(Cur))
6337  Diag(Loc, diag::err_invalid_declarator_in_block)
6338  << Name << SS.getRange();
6339  else if (isa<ExportDecl>(Cur)) {
6340  if (!isa<NamespaceDecl>(DC))
6341  Diag(Loc, diag::err_export_non_namespace_scope_name)
6342  << Name << SS.getRange();
6343  else
6344  // The cases that DC is not NamespaceDecl should be handled in
6345  // CheckRedeclarationExported.
6346  return false;
6347  } else
6348  Diag(Loc, diag::err_invalid_declarator_scope)
6349  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6350 
6351  return true;
6352  }
6353 
6354  if (Cur->isRecord()) {
6355  // Cannot qualify members within a class.
6356  Diag(Loc, diag::err_member_qualification)
6357  << Name << SS.getRange();
6358  SS.clear();
6359 
6360  // C++ constructors and destructors with incorrect scopes can break
6361  // our AST invariants by having the wrong underlying types. If
6362  // that's the case, then drop this declaration entirely.
6363  if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6364  Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6365  !Context.hasSameType(Name.getCXXNameType(),
6366  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6367  return true;
6368 
6369  return false;
6370  }
6371 
6372  // C++23 [temp.names]p5:
6373  // The keyword template shall not appear immediately after a declarative
6374  // nested-name-specifier.
6375  //
6376  // First check the template-id (if any), and then check each component of the
6377  // nested-name-specifier in reverse order.
6378  //
6379  // FIXME: nested-name-specifiers in friend declarations are declarative,
6380  // but we don't call diagnoseQualifiedDeclaration for them. We should.
6381  if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6382  Diag(Loc, diag::ext_template_after_declarative_nns)
6383  << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6384 
6385  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6386  do {
6387  if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6389  Diag(Loc, diag::ext_template_after_declarative_nns)
6391  SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6392 
6393  if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6394  if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6395  // C++23 [expr.prim.id.qual]p3:
6396  // [...] If a nested-name-specifier N is declarative and has a
6397  // simple-template-id with a template argument list A that involves a
6398  // template parameter, let T be the template nominated by N without A.
6399  // T shall be a class template.
6400  if (TST->isDependentType() && TST->isTypeAlias())
6401  Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6402  << SpecLoc.getLocalSourceRange();
6403  } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6404  // C++23 [expr.prim.id.qual]p2:
6405  // [...] A declarative nested-name-specifier shall not have a
6406  // computed-type-specifier.
6407  //
6408  // CWG2858 changed this from 'decltype-specifier' to
6409  // 'computed-type-specifier'.
6410  Diag(Loc, diag::err_computed_type_in_declarative_nns)
6411  << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6412  }
6413  }
6414  } while ((SpecLoc = SpecLoc.getPrefix()));
6415 
6416  return false;
6417 }
6418 
6420  MultiTemplateParamsArg TemplateParamLists) {
6421  // TODO: consider using NameInfo for diagnostic.
6422  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6423  DeclarationName Name = NameInfo.getName();
6424 
6425  // All of these full declarators require an identifier. If it doesn't have
6426  // one, the ParsedFreeStandingDeclSpec action should be used.
6427  if (D.isDecompositionDeclarator()) {
6428  return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6429  } else if (!Name) {
6430  if (!D.isInvalidType()) // Reject this if we think it is valid.
6431  Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6432  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6433  return nullptr;
6434  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6435  return nullptr;
6436 
6437  DeclContext *DC = CurContext;
6438  if (D.getCXXScopeSpec().isInvalid())
6439  D.setInvalidType();
6440  else if (D.getCXXScopeSpec().isSet()) {
6441  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6442  UPPC_DeclarationQualifier))
6443  return nullptr;
6444 
6445  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6446  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6447  if (!DC || isa<EnumDecl>(DC)) {
6448  // If we could not compute the declaration context, it's because the
6449  // declaration context is dependent but does not refer to a class,
6450  // class template, or class template partial specialization. Complain
6451  // and return early, to avoid the coming semantic disaster.
6452  Diag(D.getIdentifierLoc(),
6453  diag::err_template_qualified_declarator_no_match)
6454  << D.getCXXScopeSpec().getScopeRep()
6455  << D.getCXXScopeSpec().getRange();
6456  return nullptr;
6457  }
6458  bool IsDependentContext = DC->isDependentContext();
6459 
6460  if (!IsDependentContext &&
6461  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6462  return nullptr;
6463 
6464  // If a class is incomplete, do not parse entities inside it.
6465  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6466  Diag(D.getIdentifierLoc(),
6467  diag::err_member_def_undefined_record)
6468  << Name << DC << D.getCXXScopeSpec().getRange();
6469  return nullptr;
6470  }
6471  if (!D.getDeclSpec().isFriendSpecified()) {
6472  TemplateIdAnnotation *TemplateId =
6474  ? D.getName().TemplateId
6475  : nullptr;
6476  if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6477  D.getIdentifierLoc(), TemplateId,
6478  /*IsMemberSpecialization=*/false)) {
6479  if (DC->isRecord())
6480  return nullptr;
6481 
6482  D.setInvalidType();
6483  }
6484  }
6485 
6486  // Check whether we need to rebuild the type of the given
6487  // declaration in the current instantiation.
6488  if (EnteringContext && IsDependentContext &&
6489  TemplateParamLists.size() != 0) {
6490  ContextRAII SavedContext(*this, DC);
6491  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6492  D.setInvalidType();
6493  }
6494  }
6495 
6496  TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6497  QualType R = TInfo->getType();
6498 
6499  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6500  UPPC_DeclarationType))
6501  D.setInvalidType();
6502 
6503  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6504  forRedeclarationInCurContext());
6505 
6506  // See if this is a redefinition of a variable in the same scope.
6507  if (!D.getCXXScopeSpec().isSet()) {
6508  bool IsLinkageLookup = false;
6509  bool CreateBuiltins = false;
6510 
6511  // If the declaration we're planning to build will be a function
6512  // or object with linkage, then look for another declaration with
6513  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6514  //
6515  // If the declaration we're planning to build will be declared with
6516  // external linkage in the translation unit, create any builtin with
6517  // the same name.
6519  /* Do nothing*/;
6520  else if (CurContext->isFunctionOrMethod() &&
6522  R->isFunctionType())) {
6523  IsLinkageLookup = true;
6524  CreateBuiltins =
6525  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6526  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6528  CreateBuiltins = true;
6529 
6530  if (IsLinkageLookup) {
6531  Previous.clear(LookupRedeclarationWithLinkage);
6532  Previous.setRedeclarationKind(
6534  }
6535 
6536  LookupName(Previous, S, CreateBuiltins);
6537  } else { // Something like "int foo::x;"
6538  LookupQualifiedName(Previous, DC);
6539 
6540  // C++ [dcl.meaning]p1:
6541  // When the declarator-id is qualified, the declaration shall refer to a
6542  // previously declared member of the class or namespace to which the
6543  // qualifier refers (or, in the case of a namespace, of an element of the
6544  // inline namespace set of that namespace (7.3.1)) or to a specialization
6545  // thereof; [...]
6546  //
6547  // Note that we already checked the context above, and that we do not have
6548  // enough information to make sure that Previous contains the declaration
6549  // we want to match. For example, given:
6550  //
6551  // class X {
6552  // void f();
6553  // void f(float);
6554  // };
6555  //
6556  // void X::f(int) { } // ill-formed
6557  //
6558  // In this case, Previous will point to the overload set
6559  // containing the two f's declared in X, but neither of them
6560  // matches.
6561 
6563  }
6564 
6565  if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6566  TPD && TPD->isTemplateParameter()) {
6567  // Older versions of clang allowed the names of function/variable templates
6568  // to shadow the names of their template parameters. For the compatibility
6569  // purposes we detect such cases and issue a default-to-error warning that
6570  // can be disabled with -Wno-strict-primary-template-shadow.
6571  if (!D.isInvalidType()) {
6572  bool AllowForCompatibility = false;
6573  if (Scope *DeclParent = S->getDeclParent();
6574  Scope *TemplateParamParent = S->getTemplateParamParent()) {
6575  AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6576  TemplateParamParent->isDeclScope(TPD);
6577  }
6578  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6579  AllowForCompatibility);
6580  }
6581 
6582  // Just pretend that we didn't see the previous declaration.
6583  Previous.clear();
6584  }
6585 
6586  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6587  // Forget that the previous declaration is the injected-class-name.
6588  Previous.clear();
6589 
6590  // In C++, the previous declaration we find might be a tag type
6591  // (class or enum). In this case, the new declaration will hide the
6592  // tag type. Note that this applies to functions, function templates, and
6593  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6594  if (Previous.isSingleTagDecl() &&
6596  (TemplateParamLists.size() == 0 || R->isFunctionType()))
6597  Previous.clear();
6598 
6599  // Check that there are no default arguments other than in the parameters
6600  // of a function declaration (C++ only).
6601  if (getLangOpts().CPlusPlus)
6602  CheckExtraCXXDefaultArguments(D);
6603 
6604  /// Get the innermost enclosing declaration scope.
6605  S = S->getDeclParent();
6606 
6607  NamedDecl *New;
6608 
6609  bool AddToScope = true;
6611  if (TemplateParamLists.size()) {
6612  Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6613  return nullptr;
6614  }
6615 
6616  New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6617  } else if (R->isFunctionType()) {
6618  New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6619  TemplateParamLists,
6620  AddToScope);
6621  } else {
6622  New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6623  AddToScope);
6624  }
6625 
6626  if (!New)
6627  return nullptr;
6628 
6629  // If this has an identifier and is not a function template specialization,
6630  // add it to the scope stack.
6631  if (New->getDeclName() && AddToScope)
6632  PushOnScopeChains(New, S);
6633 
6634  if (OpenMP().isInOpenMPDeclareTargetContext())
6635  OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6636 
6637  return New;
6638 }
6639 
6640 /// Helper method to turn variable array types into constant array
6641 /// types in certain situations which would otherwise be errors (for
6642 /// GCC compatibility).
6644  ASTContext &Context,
6645  bool &SizeIsNegative,
6646  llvm::APSInt &Oversized) {
6647  // This method tries to turn a variable array into a constant
6648  // array even when the size isn't an ICE. This is necessary
6649  // for compatibility with code that depends on gcc's buggy
6650  // constant expression folding, like struct {char x[(int)(char*)2];}
6651  SizeIsNegative = false;
6652  Oversized = 0;
6653 
6654  if (T->isDependentType())
6655  return QualType();
6656 
6657  QualifierCollector Qs;
6658  const Type *Ty = Qs.strip(T);
6659 
6660  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6661  QualType Pointee = PTy->getPointeeType();
6662  QualType FixedType =
6663  TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6664  Oversized);
6665  if (FixedType.isNull()) return FixedType;
6666  FixedType = Context.getPointerType(FixedType);
6667  return Qs.apply(Context, FixedType);
6668  }
6669  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6670  QualType Inner = PTy->getInnerType();
6671  QualType FixedType =
6672  TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6673  Oversized);
6674  if (FixedType.isNull()) return FixedType;
6675  FixedType = Context.getParenType(FixedType);
6676  return Qs.apply(Context, FixedType);
6677  }
6678 
6679  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6680  if (!VLATy)
6681  return QualType();
6682 
6683  QualType ElemTy = VLATy->getElementType();
6684  if (ElemTy->isVariablyModifiedType()) {
6685  ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6686  SizeIsNegative, Oversized);
6687  if (ElemTy.isNull())
6688  return QualType();
6689  }
6690 
6691  Expr::EvalResult Result;
6692  if (!VLATy->getSizeExpr() ||
6693  !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6694  return QualType();
6695 
6696  llvm::APSInt Res = Result.Val.getInt();
6697 
6698  // Check whether the array size is negative.
6699  if (Res.isSigned() && Res.isNegative()) {
6700  SizeIsNegative = true;
6701  return QualType();
6702  }
6703 
6704  // Check whether the array is too large to be addressed.
6705  unsigned ActiveSizeBits =
6706  (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6707  !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6708  ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6709  : Res.getActiveBits();
6710  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6711  Oversized = Res;
6712  return QualType();
6713  }
6714 
6715  QualType FoldedArrayType = Context.getConstantArrayType(
6716  ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6717  return Qs.apply(Context, FoldedArrayType);
6718 }
6719 
6720 static void
6722  SrcTL = SrcTL.getUnqualifiedLoc();
6723  DstTL = DstTL.getUnqualifiedLoc();
6724  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6725  PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6726  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6727  DstPTL.getPointeeLoc());
6728  DstPTL.setStarLoc(SrcPTL.getStarLoc());
6729  return;
6730  }
6731  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6732  ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6733  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6734  DstPTL.getInnerLoc());
6735  DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6736  DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6737  return;
6738  }
6739  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6740  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6741  TypeLoc SrcElemTL = SrcATL.getElementLoc();
6742  TypeLoc DstElemTL = DstATL.getElementLoc();
6743  if (VariableArrayTypeLoc SrcElemATL =
6744  SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6745  ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6746  FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6747  } else {
6748  DstElemTL.initializeFullCopy(SrcElemTL);
6749  }
6750  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6751  DstATL.setSizeExpr(SrcATL.getSizeExpr());
6752  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6753 }
6754 
6755 /// Helper method to turn variable array types into constant array
6756 /// types in certain situations which would otherwise be errors (for
6757 /// GCC compatibility).
6758 static TypeSourceInfo*
6760  ASTContext &Context,
6761  bool &SizeIsNegative,
6762  llvm::APSInt &Oversized) {
6763  QualType FixedTy
6764  = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6765  SizeIsNegative, Oversized);
6766  if (FixedTy.isNull())
6767  return nullptr;
6768  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6770  FixedTInfo->getTypeLoc());
6771  return FixedTInfo;
6772 }
6773 
6774 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6775 /// true if we were successful.
6777  QualType &T, SourceLocation Loc,
6778  unsigned FailedFoldDiagID) {
6779  bool SizeIsNegative;
6780  llvm::APSInt Oversized;
6782  TInfo, Context, SizeIsNegative, Oversized);
6783  if (FixedTInfo) {
6784  Diag(Loc, diag::ext_vla_folded_to_constant);
6785  TInfo = FixedTInfo;
6786  T = FixedTInfo->getType();
6787  return true;
6788  }
6789 
6790  if (SizeIsNegative)
6791  Diag(Loc, diag::err_typecheck_negative_array_size);
6792  else if (Oversized.getBoolValue())
6793  Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6794  else if (FailedFoldDiagID)
6795  Diag(Loc, FailedFoldDiagID);
6796  return false;
6797 }
6798 
6799 /// Register the given locally-scoped extern "C" declaration so
6800 /// that it can be found later for redeclarations. We include any extern "C"
6801 /// declaration that is not visible in the translation unit here, not just
6802 /// function-scope declarations.
6803 void
6805  if (!getLangOpts().CPlusPlus &&
6807  // Don't need to track declarations in the TU in C.
6808  return;
6809 
6810  // Note that we have a locally-scoped external with this name.
6812 }
6813 
6815  // FIXME: We can have multiple results via __attribute__((overloadable)).
6816  auto Result = Context.getExternCContextDecl()->lookup(Name);
6817  return Result.empty() ? nullptr : *Result.begin();
6818 }
6819 
6820 /// Diagnose function specifiers on a declaration of an identifier that
6821 /// does not identify a function.
6823  // FIXME: We should probably indicate the identifier in question to avoid
6824  // confusion for constructs like "virtual int a(), b;"
6825  if (DS.isVirtualSpecified())
6826  Diag(DS.getVirtualSpecLoc(),
6827  diag::err_virtual_non_function);
6828 
6829  if (DS.hasExplicitSpecifier())
6830  Diag(DS.getExplicitSpecLoc(),
6831  diag::err_explicit_non_function);
6832 
6833  if (DS.isNoreturnSpecified())
6834  Diag(DS.getNoreturnSpecLoc(),
6835  diag::err_noreturn_non_function);
6836 }
6837 
6838 NamedDecl*
6841  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6842  if (D.getCXXScopeSpec().isSet()) {
6843  Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6844  << D.getCXXScopeSpec().getRange();
6845  D.setInvalidType();
6846  // Pretend we didn't see the scope specifier.
6847  DC = CurContext;
6848  Previous.clear();
6849  }
6850 
6851  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6852 
6853  if (D.getDeclSpec().isInlineSpecified())
6854  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6855  << getLangOpts().CPlusPlus17;
6857  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6858  << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6859 
6863  diag::err_deduction_guide_invalid_specifier)
6864  << "typedef";
6865  else
6866  Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6867  << D.getName().getSourceRange();
6868  return nullptr;
6869  }
6870 
6871  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6872  if (!NewTD) return nullptr;
6873 
6874  // Handle attributes prior to checking for duplicates in MergeVarDecl
6875  ProcessDeclAttributes(S, NewTD, D);
6876 
6877  CheckTypedefForVariablyModifiedType(S, NewTD);
6878 
6879  bool Redeclaration = D.isRedeclaration();
6880  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6881  D.setRedeclaration(Redeclaration);
6882  return ND;
6883 }
6884 
6885 void
6887  // C99 6.7.7p2: If a typedef name specifies a variably modified type
6888  // then it shall have block scope.
6889  // Note that variably modified types must be fixed before merging the decl so
6890  // that redeclarations will match.
6891  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6892  QualType T = TInfo->getType();
6893  if (T->isVariablyModifiedType()) {
6894  setFunctionHasBranchProtectedScope();
6895 
6896  if (S->getFnParent() == nullptr) {
6897  bool SizeIsNegative;
6898  llvm::APSInt Oversized;
6899  TypeSourceInfo *FixedTInfo =
6901  SizeIsNegative,
6902  Oversized);
6903  if (FixedTInfo) {
6904  Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6905  NewTD->setTypeSourceInfo(FixedTInfo);
6906  } else {
6907  if (SizeIsNegative)
6908  Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6909  else if (T->isVariableArrayType())
6910  Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6911  else if (Oversized.getBoolValue())
6912  Diag(NewTD->getLocation(), diag::err_array_too_large)
6913  << toString(Oversized, 10);
6914  else
6915  Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6916  NewTD->setInvalidDecl();
6917  }
6918  }
6919  }
6920 }
6921 
6922 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6923 /// declares a typedef-name, either using the 'typedef' type specifier or via
6924 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6925 NamedDecl*
6927  LookupResult &Previous, bool &Redeclaration) {
6928 
6929  // Find the shadowed declaration before filtering for scope.
6930  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6931 
6932  // Merge the decl with the existing one if appropriate. If the decl is
6933  // in an outer scope, it isn't the same thing.
6934  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6935  /*AllowInlineNamespace*/false);
6937  if (!Previous.empty()) {
6938  Redeclaration = true;
6939  MergeTypedefNameDecl(S, NewTD, Previous);
6940  } else {
6941  inferGslPointerAttribute(NewTD);
6942  }
6943 
6944  if (ShadowedDecl && !Redeclaration)
6945  CheckShadow(NewTD, ShadowedDecl, Previous);
6946 
6947  // If this is the C FILE type, notify the AST context.
6948  if (IdentifierInfo *II = NewTD->getIdentifier())
6949  if (!NewTD->isInvalidDecl() &&
6951  switch (II->getNotableIdentifierID()) {
6952  case tok::NotableIdentifierKind::FILE:
6953  Context.setFILEDecl(NewTD);
6954  break;
6955  case tok::NotableIdentifierKind::jmp_buf:
6956  Context.setjmp_bufDecl(NewTD);
6957  break;
6958  case tok::NotableIdentifierKind::sigjmp_buf:
6959  Context.setsigjmp_bufDecl(NewTD);
6960  break;
6961  case tok::NotableIdentifierKind::ucontext_t:
6962  Context.setucontext_tDecl(NewTD);
6963  break;
6964  case tok::NotableIdentifierKind::float_t:
6965  case tok::NotableIdentifierKind::double_t:
6966  NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6967  break;
6968  default:
6969  break;
6970  }
6971  }
6972 
6973  return NewTD;
6974 }
6975 
6976 /// Determines whether the given declaration is an out-of-scope
6977 /// previous declaration.
6978 ///
6979 /// This routine should be invoked when name lookup has found a
6980 /// previous declaration (PrevDecl) that is not in the scope where a
6981 /// new declaration by the same name is being introduced. If the new
6982 /// declaration occurs in a local scope, previous declarations with
6983 /// linkage may still be considered previous declarations (C99
6984 /// 6.2.2p4-5, C++ [basic.link]p6).
6985 ///
6986 /// \param PrevDecl the previous declaration found by name
6987 /// lookup
6988 ///
6989 /// \param DC the context in which the new declaration is being
6990 /// declared.
6991 ///
6992 /// \returns true if PrevDecl is an out-of-scope previous declaration
6993 /// for a new delcaration with the same name.
6994 static bool
6996  ASTContext &Context) {
6997  if (!PrevDecl)
6998  return false;
6999 
7000  if (!PrevDecl->hasLinkage())
7001  return false;
7002 
7003  if (Context.getLangOpts().CPlusPlus) {
7004  // C++ [basic.link]p6:
7005  // If there is a visible declaration of an entity with linkage
7006  // having the same name and type, ignoring entities declared
7007  // outside the innermost enclosing namespace scope, the block
7008  // scope declaration declares that same entity and receives the
7009  // linkage of the previous declaration.
7010  DeclContext *OuterContext = DC->getRedeclContext();
7011  if (!OuterContext->isFunctionOrMethod())
7012  // This rule only applies to block-scope declarations.
7013  return false;
7014 
7015  DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7016  if (PrevOuterContext->isRecord())
7017  // We found a member function: ignore it.
7018  return false;
7019 
7020  // Find the innermost enclosing namespace for the new and
7021  // previous declarations.
7022  OuterContext = OuterContext->getEnclosingNamespaceContext();
7023  PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7024 
7025  // The previous declaration is in a different namespace, so it
7026  // isn't the same function.
7027  if (!OuterContext->Equals(PrevOuterContext))
7028  return false;
7029  }
7030 
7031  return true;
7032 }
7033 
7035  CXXScopeSpec &SS = D.getCXXScopeSpec();
7036  if (!SS.isSet()) return;
7038 }
7039 
7041  QualType type = decl->getType();
7042  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
7043  if (lifetime == Qualifiers::OCL_Autoreleasing) {
7044  // Various kinds of declaration aren't allowed to be __autoreleasing.
7045  unsigned kind = -1U;
7046  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
7047  if (var->hasAttr<BlocksAttr>())
7048  kind = 0; // __block
7049  else if (!var->hasLocalStorage())
7050  kind = 1; // global
7051  } else if (isa<ObjCIvarDecl>(decl)) {
7052  kind = 3; // ivar
7053  } else if (isa<FieldDecl>(decl)) {
7054  kind = 2; // field
7055  }
7056 
7057  if (kind != -1U) {
7058  Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
7059  << kind;
7060  }
7061  } else if (lifetime == Qualifiers::OCL_None) {
7062  // Try to infer lifetime.
7063  if (!type->isObjCLifetimeType())
7064  return false;
7065 
7066  lifetime = type->getObjCARCImplicitLifetime();
7067  type = Context.getLifetimeQualifiedType(type, lifetime);
7068  decl->setType(type);
7069  }
7070 
7071  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
7072  // Thread-local variables cannot have lifetime.
7073  if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
7074  var->getTLSKind()) {
7075  Diag(var->getLocation(), diag::err_arc_thread_ownership)
7076  << var->getType();
7077  return true;
7078  }
7079  }
7080 
7081  return false;
7082 }
7083 
7085  if (Decl->getType().hasAddressSpace())
7086  return;
7087  if (Decl->getType()->isDependentType())
7088  return;
7089  if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7090  QualType Type = Var->getType();
7091  if (Type->isSamplerT() || Type->isVoidType())
7092  return;
7093  LangAS ImplAS = LangAS::opencl_private;
7094  // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7095  // __opencl_c_program_scope_global_variables feature, the address space
7096  // for a variable at program scope or a static or extern variable inside
7097  // a function are inferred to be __global.
7098  if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7099  Var->hasGlobalStorage())
7100  ImplAS = LangAS::opencl_global;
7101  // If the original type from a decayed type is an array type and that array
7102  // type has no address space yet, deduce it now.
7103  if (auto DT = dyn_cast<DecayedType>(Type)) {
7104  auto OrigTy = DT->getOriginalType();
7105  if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7106  // Add the address space to the original array type and then propagate
7107  // that to the element type through `getAsArrayType`.
7108  OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7109  OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7110  // Re-generate the decayed type.
7111  Type = Context.getDecayedType(OrigTy);
7112  }
7113  }
7114  Type = Context.getAddrSpaceQualType(Type, ImplAS);
7115  // Apply any qualifiers (including address space) from the array type to
7116  // the element type. This implements C99 6.7.3p8: "If the specification of
7117  // an array type includes any type qualifiers, the element type is so
7118  // qualified, not the array type."
7119  if (Type->isArrayType())
7120  Type = QualType(Context.getAsArrayType(Type), 0);
7121  Decl->setType(Type);
7122  }
7123 }
7124 
7126  // Ensure that an auto decl is deduced otherwise the checks below might cache
7127  // the wrong linkage.
7128  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7129 
7130  // 'weak' only applies to declarations with external linkage.
7131  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7132  if (!ND.isExternallyVisible()) {
7133  S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7134  ND.dropAttr<WeakAttr>();
7135  }
7136  }
7137  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7138  if (ND.isExternallyVisible()) {
7139  S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7140  ND.dropAttrs<WeakRefAttr, AliasAttr>();
7141  }
7142  }
7143 
7144  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7145  if (VD->hasInit()) {
7146  if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7147  assert(VD->isThisDeclarationADefinition() &&
7148  !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7149  S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7150  VD->dropAttr<AliasAttr>();
7151  }
7152  }
7153  }
7154 
7155  // 'selectany' only applies to externally visible variable declarations.
7156  // It does not apply to functions.
7157  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7158  if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7159  S.Diag(Attr->getLocation(),
7160  diag::err_attribute_selectany_non_extern_data);
7161  ND.dropAttr<SelectAnyAttr>();
7162  }
7163  }
7164 
7165  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7166  auto *VD = dyn_cast<VarDecl>(&ND);
7167  bool IsAnonymousNS = false;
7168  bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7169  if (VD) {
7170  const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7171  while (NS && !IsAnonymousNS) {
7172  IsAnonymousNS = NS->isAnonymousNamespace();
7173  NS = dyn_cast<NamespaceDecl>(NS->getParent());
7174  }
7175  }
7176  // dll attributes require external linkage. Static locals may have external
7177  // linkage but still cannot be explicitly imported or exported.
7178  // In Microsoft mode, a variable defined in anonymous namespace must have
7179  // external linkage in order to be exported.
7180  bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7181  if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7182  (!AnonNSInMicrosoftMode &&
7183  (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7184  S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7185  << &ND << Attr;
7186  ND.setInvalidDecl();
7187  }
7188  }
7189 
7190  // Check the attributes on the function type, if any.
7191  if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7192  // Don't declare this variable in the second operand of the for-statement;
7193  // GCC miscompiles that by ending its lifetime before evaluating the
7194  // third operand. See gcc.gnu.org/PR86769.
7195  AttributedTypeLoc ATL;
7196  for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7197  (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7198  TL = ATL.getModifiedLoc()) {
7199  // The [[lifetimebound]] attribute can be applied to the implicit object
7200  // parameter of a non-static member function (other than a ctor or dtor)
7201  // by applying it to the function type.
7202  if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7203  const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7204  if (!MD || MD->isStatic()) {
7205  S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7206  << !MD << A->getRange();
7207  } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7208  S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7209  << isa<CXXDestructorDecl>(MD) << A->getRange();
7210  }
7211  }
7212  }
7213  }
7214 }
7215 
7217  NamedDecl *NewDecl,
7218  bool IsSpecialization,
7219  bool IsDefinition) {
7220  if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7221  return;
7222 
7223  bool IsTemplate = false;
7224  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7225  OldDecl = OldTD->getTemplatedDecl();
7226  IsTemplate = true;
7227  if (!IsSpecialization)
7228  IsDefinition = false;
7229  }
7230  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7231  NewDecl = NewTD->getTemplatedDecl();
7232  IsTemplate = true;
7233  }
7234 
7235  if (!OldDecl || !NewDecl)
7236  return;
7237 
7238  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7239  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7240  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7241  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7242 
7243  // dllimport and dllexport are inheritable attributes so we have to exclude
7244  // inherited attribute instances.
7245  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7246  (NewExportAttr && !NewExportAttr->isInherited());
7247 
7248  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7249  // the only exception being explicit specializations.
7250  // Implicitly generated declarations are also excluded for now because there
7251  // is no other way to switch these to use dllimport or dllexport.
7252  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7253 
7254  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7255  // Allow with a warning for free functions and global variables.
7256  bool JustWarn = false;
7257  if (!OldDecl->isCXXClassMember()) {
7258  auto *VD = dyn_cast<VarDecl>(OldDecl);
7259  if (VD && !VD->getDescribedVarTemplate())
7260  JustWarn = true;
7261  auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7262  if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7263  JustWarn = true;
7264  }
7265 
7266  // We cannot change a declaration that's been used because IR has already
7267  // been emitted. Dllimported functions will still work though (modulo
7268  // address equality) as they can use the thunk.
7269  if (OldDecl->isUsed())
7270  if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7271  JustWarn = false;
7272 
7273  unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7274  : diag::err_attribute_dll_redeclaration;
7275  S.Diag(NewDecl->getLocation(), DiagID)
7276  << NewDecl
7277  << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7278  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7279  if (!JustWarn) {
7280  NewDecl->setInvalidDecl();
7281  return;
7282  }
7283  }
7284 
7285  // A redeclaration is not allowed to drop a dllimport attribute, the only
7286  // exceptions being inline function definitions (except for function
7287  // templates), local extern declarations, qualified friend declarations or
7288  // special MSVC extension: in the last case, the declaration is treated as if
7289  // it were marked dllexport.
7290  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7291  bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7292  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7293  // Ignore static data because out-of-line definitions are diagnosed
7294  // separately.
7295  IsStaticDataMember = VD->isStaticDataMember();
7296  IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7298  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7299  IsInline = FD->isInlined();
7300  IsQualifiedFriend = FD->getQualifier() &&
7301  FD->getFriendObjectKind() == Decl::FOK_Declared;
7302  }
7303 
7304  if (OldImportAttr && !HasNewAttr &&
7305  (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7306  !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7307  if (IsMicrosoftABI && IsDefinition) {
7308  if (IsSpecialization) {
7309  S.Diag(
7310  NewDecl->getLocation(),
7311  diag::err_attribute_dllimport_function_specialization_definition);
7312  S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7313  NewDecl->dropAttr<DLLImportAttr>();
7314  } else {
7315  S.Diag(NewDecl->getLocation(),
7316  diag::warn_redeclaration_without_import_attribute)
7317  << NewDecl;
7318  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7319  NewDecl->dropAttr<DLLImportAttr>();
7320  NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7321  S.Context, NewImportAttr->getRange()));
7322  }
7323  } else if (IsMicrosoftABI && IsSpecialization) {
7324  assert(!IsDefinition);
7325  // MSVC allows this. Keep the inherited attribute.
7326  } else {
7327  S.Diag(NewDecl->getLocation(),
7328  diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7329  << NewDecl << OldImportAttr;
7330  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7331  S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7332  OldDecl->dropAttr<DLLImportAttr>();
7333  NewDecl->dropAttr<DLLImportAttr>();
7334  }
7335  } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7336  // In MinGW, seeing a function declared inline drops the dllimport
7337  // attribute.
7338  OldDecl->dropAttr<DLLImportAttr>();
7339  NewDecl->dropAttr<DLLImportAttr>();
7340  S.Diag(NewDecl->getLocation(),
7341  diag::warn_dllimport_dropped_from_inline_function)
7342  << NewDecl << OldImportAttr;
7343  }
7344 
7345  // A specialization of a class template member function is processed here
7346  // since it's a redeclaration. If the parent class is dllexport, the
7347  // specialization inherits that attribute. This doesn't happen automatically
7348  // since the parent class isn't instantiated until later.
7349  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7350  if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7351  !NewImportAttr && !NewExportAttr) {
7352  if (const DLLExportAttr *ParentExportAttr =
7353  MD->getParent()->getAttr<DLLExportAttr>()) {
7354  DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7355  NewAttr->setInherited(true);
7356  NewDecl->addAttr(NewAttr);
7357  }
7358  }
7359  }
7360 }
7361 
7362 /// Given that we are within the definition of the given function,
7363 /// will that definition behave like C99's 'inline', where the
7364 /// definition is discarded except for optimization purposes?
7366  // Try to avoid calling GetGVALinkageForFunction.
7367 
7368  // All cases of this require the 'inline' keyword.
7369  if (!FD->isInlined()) return false;
7370 
7371  // This is only possible in C++ with the gnu_inline attribute.
7372  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7373  return false;
7374 
7375  // Okay, go ahead and call the relatively-more-expensive function.
7377 }
7378 
7379 /// Determine whether a variable is extern "C" prior to attaching
7380 /// an initializer. We can't just call isExternC() here, because that
7381 /// will also compute and cache whether the declaration is externally
7382 /// visible, which might change when we attach the initializer.
7383 ///
7384 /// This can only be used if the declaration is known to not be a
7385 /// redeclaration of an internal linkage declaration.
7386 ///
7387 /// For instance:
7388 ///
7389 /// auto x = []{};
7390 ///
7391 /// Attaching the initializer here makes this declaration not externally
7392 /// visible, because its type has internal linkage.
7393 ///
7394 /// FIXME: This is a hack.
7395 template<typename T>
7396 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7397  if (S.getLangOpts().CPlusPlus) {
7398  // In C++, the overloadable attribute negates the effects of extern "C".
7399  if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7400  return false;
7401 
7402  // So do CUDA's host/device attributes.
7403  if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7404  D->template hasAttr<CUDAHostAttr>()))
7405  return false;
7406  }
7407  return D->isExternC();
7408 }
7409 
7410 static bool shouldConsiderLinkage(const VarDecl *VD) {
7411  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7412  if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7413  isa<OMPDeclareMapperDecl>(DC))
7414  return VD->hasExternalStorage();
7415  if (DC->isFileContext())
7416  return true;
7417  if (DC->isRecord())
7418  return false;
7419  if (DC->getDeclKind() == Decl::HLSLBuffer)
7420  return false;
7421 
7422  if (isa<RequiresExprBodyDecl>(DC))
7423  return false;
7424  llvm_unreachable("Unexpected context");
7425 }
7426 
7427 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7428  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7429  if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7430  isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7431  return true;
7432  if (DC->isRecord())
7433  return false;
7434  llvm_unreachable("Unexpected context");
7435 }
7436 
7437 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7439  // Check decl attributes on the DeclSpec.
7441  return true;
7442 
7443  // Walk the declarator structure, checking decl attributes that were in a type
7444  // position to the decl itself.
7445  for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7446  if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7447  return true;
7448  }
7449 
7450  // Finally, check attributes on the decl itself.
7451  return PD.getAttributes().hasAttribute(Kind) ||
7453 }
7454 
7455 /// Adjust the \c DeclContext for a function or variable that might be a
7456 /// function-local external declaration.
7458  if (!DC->isFunctionOrMethod())
7459  return false;
7460 
7461  // If this is a local extern function or variable declared within a function
7462  // template, don't add it into the enclosing namespace scope until it is
7463  // instantiated; it might have a dependent type right now.
7464  if (DC->isDependentContext())
7465  return true;
7466 
7467  // C++11 [basic.link]p7:
7468  // When a block scope declaration of an entity with linkage is not found to
7469  // refer to some other declaration, then that entity is a member of the
7470  // innermost enclosing namespace.
7471  //
7472  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7473  // semantically-enclosing namespace, not a lexically-enclosing one.
7474  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7475  DC = DC->getParent();
7476  return true;
7477 }
7478 
7479 /// Returns true if given declaration has external C language linkage.
7480 static bool isDeclExternC(const Decl *D) {
7481  if (const auto *FD = dyn_cast<FunctionDecl>(D))
7482  return FD->isExternC();
7483  if (const auto *VD = dyn_cast<VarDecl>(D))
7484  return VD->isExternC();
7485 
7486  llvm_unreachable("Unknown type of decl!");
7487 }
7488 
7489 /// Returns true if there hasn't been any invalid type diagnosed.
7490 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7491  DeclContext *DC = NewVD->getDeclContext();
7492  QualType R = NewVD->getType();
7493 
7494  // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7495  // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7496  // argument.
7497  if (!R->isSampledImageType() && (R->isImageType() || R->isPipeType())) {
7498  Se.Diag(NewVD->getLocation(),
7499  diag::err_opencl_type_can_only_be_used_as_function_parameter)
7500  << R;
7501  NewVD->setInvalidDecl();
7502  return false;
7503  }
7504 
7505  // OpenCL v1.2 s6.9.r:
7506  // The event type cannot be used to declare a program scope variable.
7507  // OpenCL v2.0 s6.9.q:
7508  // The clk_event_t and reserve_id_t types cannot be declared in program
7509  // scope.
7510  if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7511  if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7512  Se.Diag(NewVD->getLocation(),
7513  diag::err_invalid_type_for_program_scope_var)
7514  << R;
7515  NewVD->setInvalidDecl();
7516  return false;
7517  }
7518  }
7519 
7520  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7521  if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7522  Se.getLangOpts())) {
7523  QualType NR = R.getCanonicalType();
7524  while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7525  NR->isReferenceType()) {
7527  NR->isFunctionReferenceType()) {
7528  Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7529  << NR->isReferenceType();
7530  NewVD->setInvalidDecl();
7531  return false;
7532  }
7533  NR = NR->getPointeeType();
7534  }
7535  }
7536 
7537  if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7538  Se.getLangOpts())) {
7539  // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7540  // half array type (unless the cl_khr_fp16 extension is enabled).
7541  if (Se.Context.getBaseElementType(R)->isHalfType()) {
7542  Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7543  NewVD->setInvalidDecl();
7544  return false;
7545  }
7546  }
7547 
7548  // OpenCL v1.2 s6.9.r:
7549  // The event type cannot be used with the __local, __constant and __global
7550  // address space qualifiers.
7551  if (R->isEventT()) {
7553  Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7554  NewVD->setInvalidDecl();
7555  return false;
7556  }
7557  }
7558 
7559  if (R->isSamplerT()) {
7560  // OpenCL v1.2 s6.9.b p4:
7561  // The sampler type cannot be used with the __local and __global address
7562  // space qualifiers.
7565  Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7566  NewVD->setInvalidDecl();
7567  }
7568 
7569  // OpenCL v1.2 s6.12.14.1:
7570  // A global sampler must be declared with either the constant address
7571  // space qualifier or with the const qualifier.
7572  if (DC->isTranslationUnit() &&
7574  R.isConstQualified())) {
7575  Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7576  NewVD->setInvalidDecl();
7577  }
7578  if (NewVD->isInvalidDecl())
7579  return false;
7580  }
7581 
7582  return true;
7583 }
7584 
7585 template <typename AttrTy>
7586 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7587  const TypedefNameDecl *TND = TT->getDecl();
7588  if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7589  AttrTy *Clone = Attribute->clone(S.Context);
7590  Clone->setInherited(true);
7591  D->addAttr(Clone);
7592  }
7593 }
7594 
7595 // This function emits warning and a corresponding note based on the
7596 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7597 // declarations of an annotated type must be const qualified.
7599  QualType VarType = VD->getType().getCanonicalType();
7600 
7601  // Ignore local declarations (for now) and those with const qualification.
7602  // TODO: Local variables should not be allowed if their type declaration has
7603  // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7604  if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7605  return;
7606 
7607  if (VarType->isArrayType()) {
7608  // Retrieve element type for array declarations.
7609  VarType = S.getASTContext().getBaseElementType(VarType);
7610  }
7611 
7612  const RecordDecl *RD = VarType->getAsRecordDecl();
7613 
7614  // Check if the record declaration is present and if it has any attributes.
7615  if (RD == nullptr)
7616  return;
7617 
7618  if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7619  S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7620  S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7621  return;
7622  }
7623 }
7624 
7626  Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7627  LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7628  bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7629  QualType R = TInfo->getType();
7630  DeclarationName Name = GetNameForDeclarator(D).getName();
7631 
7632  IdentifierInfo *II = Name.getAsIdentifierInfo();
7633  bool IsPlaceholderVariable = false;
7634 
7635  if (D.isDecompositionDeclarator()) {
7636  // Take the name of the first declarator as our name for diagnostic
7637  // purposes.
7638  auto &Decomp = D.getDecompositionDeclarator();
7639  if (!Decomp.bindings().empty()) {
7640  II = Decomp.bindings()[0].Name;
7641  Name = II;
7642  }
7643  } else if (!II) {
7644  Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7645  return nullptr;
7646  }
7647 
7648 
7651 
7652  if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7653  SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7654  IsPlaceholderVariable = true;
7655  if (!Previous.empty()) {
7656  NamedDecl *PrevDecl = *Previous.begin();
7657  bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7658  DC->getRedeclContext());
7659  if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7660  DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7661  }
7662  }
7663 
7664  // dllimport globals without explicit storage class are treated as extern. We
7665  // have to change the storage class this early to get the right DeclContext.
7666  if (SC == SC_None && !DC->isRecord() &&
7667  hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7668  !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7669  SC = SC_Extern;
7670 
7671  DeclContext *OriginalDC = DC;
7672  bool IsLocalExternDecl = SC == SC_Extern &&
7673  adjustContextForLocalExternDecl(DC);
7674 
7675  if (SCSpec == DeclSpec::SCS_mutable) {
7676  // mutable can only appear on non-static class members, so it's always
7677  // an error here
7678  Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7679  D.setInvalidType();
7680  SC = SC_None;
7681  }
7682 
7683  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7684  !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7686  // In C++11, the 'register' storage class specifier is deprecated.
7687  // Suppress the warning in system macros, it's used in macros in some
7688  // popular C system headers, such as in glibc's htonl() macro.
7690  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7691  : diag::warn_deprecated_register)
7693  }
7694 
7695  DiagnoseFunctionSpecifiers(D.getDeclSpec());
7696 
7697  if (!DC->isRecord() && S->getFnParent() == nullptr) {
7698  // C99 6.9p2: The storage-class specifiers auto and register shall not
7699  // appear in the declaration specifiers in an external declaration.
7700  // Global Register+Asm is a GNU extension we support.
7701  if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7702  Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7703  D.setInvalidType();
7704  }
7705  }
7706 
7707  // If this variable has a VLA type and an initializer, try to
7708  // fold to a constant-sized type. This is otherwise invalid.
7709  if (D.hasInitializer() && R->isVariableArrayType())
7710  tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7711  /*DiagID=*/0);
7712 
7713  bool IsMemberSpecialization = false;
7714  bool IsVariableTemplateSpecialization = false;
7715  bool IsPartialSpecialization = false;
7716  bool IsVariableTemplate = false;
7717  VarDecl *NewVD = nullptr;
7718  VarTemplateDecl *NewTemplate = nullptr;
7719  TemplateParameterList *TemplateParams = nullptr;
7720  if (!getLangOpts().CPlusPlus) {
7721  NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7722  II, R, TInfo, SC);
7723 
7724  if (R->getContainedDeducedType())
7725  ParsingInitForAutoVars.insert(NewVD);
7726 
7727  if (D.isInvalidType())
7728  NewVD->setInvalidDecl();
7729 
7731  NewVD->hasLocalStorage())
7732  checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7733  NTCUC_AutoVar, NTCUK_Destruct);
7734  } else {
7735  bool Invalid = false;
7736 
7737  if (DC->isRecord() && !CurContext->isRecord()) {
7738  // This is an out-of-line definition of a static data member.
7739  switch (SC) {
7740  case SC_None:
7741  break;
7742  case SC_Static:
7744  diag::err_static_out_of_line)
7746  break;
7747  case SC_Auto:
7748  case SC_Register:
7749  case SC_Extern:
7750  // [dcl.stc] p2: The auto or register specifiers shall be applied only
7751  // to names of variables declared in a block or to function parameters.
7752  // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7753  // of class members
7754 
7756  diag::err_storage_class_for_static_member)
7758  break;
7759  case SC_PrivateExtern:
7760  llvm_unreachable("C storage class in c++!");
7761  }
7762  }
7763 
7764  if (SC == SC_Static && CurContext->isRecord()) {
7765  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7766  // Walk up the enclosing DeclContexts to check for any that are
7767  // incompatible with static data members.
7768  const DeclContext *FunctionOrMethod = nullptr;
7769  const CXXRecordDecl *AnonStruct = nullptr;
7770  for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7771  if (Ctxt->isFunctionOrMethod()) {
7772  FunctionOrMethod = Ctxt;
7773  break;
7774  }
7775  const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7776  if (ParentDecl && !ParentDecl->getDeclName()) {
7777  AnonStruct = ParentDecl;
7778  break;
7779  }
7780  }
7781  if (FunctionOrMethod) {
7782  // C++ [class.static.data]p5: A local class shall not have static data
7783  // members.
7784  Diag(D.getIdentifierLoc(),
7785  diag::err_static_data_member_not_allowed_in_local_class)
7786  << Name << RD->getDeclName()
7787  << llvm::to_underlying(RD->getTagKind());
7788  } else if (AnonStruct) {
7789  // C++ [class.static.data]p4: Unnamed classes and classes contained
7790  // directly or indirectly within unnamed classes shall not contain
7791  // static data members.
7792  Diag(D.getIdentifierLoc(),
7793  diag::err_static_data_member_not_allowed_in_anon_struct)
7794  << Name << llvm::to_underlying(AnonStruct->getTagKind());
7795  Invalid = true;
7796  } else if (RD->isUnion()) {
7797  // C++98 [class.union]p1: If a union contains a static data member,
7798  // the program is ill-formed. C++11 drops this restriction.
7799  Diag(D.getIdentifierLoc(),
7800  getLangOpts().CPlusPlus11
7801  ? diag::warn_cxx98_compat_static_data_member_in_union
7802  : diag::ext_static_data_member_in_union) << Name;
7803  }
7804  }
7805  }
7806 
7807  // Match up the template parameter lists with the scope specifier, then
7808  // determine whether we have a template or a template specialization.
7809  bool InvalidScope = false;
7810  TemplateParams = MatchTemplateParametersToScopeSpecifier(
7812  D.getCXXScopeSpec(),
7814  ? D.getName().TemplateId
7815  : nullptr,
7816  TemplateParamLists,
7817  /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7818  Invalid |= InvalidScope;
7819 
7820  if (TemplateParams) {
7821  if (!TemplateParams->size() &&
7823  // There is an extraneous 'template<>' for this variable. Complain
7824  // about it, but allow the declaration of the variable.
7825  Diag(TemplateParams->getTemplateLoc(),
7826  diag::err_template_variable_noparams)
7827  << II
7828  << SourceRange(TemplateParams->getTemplateLoc(),
7829  TemplateParams->getRAngleLoc());
7830  TemplateParams = nullptr;
7831  } else {
7832  // Check that we can declare a template here.
7833  if (CheckTemplateDeclScope(S, TemplateParams))
7834  return nullptr;
7835 
7837  // This is an explicit specialization or a partial specialization.
7838  IsVariableTemplateSpecialization = true;
7839  IsPartialSpecialization = TemplateParams->size() > 0;
7840  } else { // if (TemplateParams->size() > 0)
7841  // This is a template declaration.
7842  IsVariableTemplate = true;
7843 
7844  // Only C++1y supports variable templates (N3651).
7845  Diag(D.getIdentifierLoc(),
7846  getLangOpts().CPlusPlus14
7847  ? diag::warn_cxx11_compat_variable_template
7848  : diag::ext_variable_template);
7849  }
7850  }
7851  } else {
7852  // Check that we can declare a member specialization here.
7853  if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7854  CheckTemplateDeclScope(S, TemplateParamLists.back()))
7855  return nullptr;
7856  assert((Invalid ||
7858  "should have a 'template<>' for this decl");
7859  }
7860 
7861  if (IsVariableTemplateSpecialization) {
7862  SourceLocation TemplateKWLoc =
7863  TemplateParamLists.size() > 0
7864  ? TemplateParamLists[0]->getTemplateLoc()
7865  : SourceLocation();
7866  DeclResult Res = ActOnVarTemplateSpecialization(
7867  S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7869  if (Res.isInvalid())
7870  return nullptr;
7871  NewVD = cast<VarDecl>(Res.get());
7872  AddToScope = false;
7873  } else if (D.isDecompositionDeclarator()) {
7874  NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7875  D.getIdentifierLoc(), R, TInfo, SC,
7876  Bindings);
7877  } else
7878  NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7879  D.getIdentifierLoc(), II, R, TInfo, SC);
7880 
7881  // If this is supposed to be a variable template, create it as such.
7882  if (IsVariableTemplate) {
7883  NewTemplate =
7884  VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7885  TemplateParams, NewVD);
7886  NewVD->setDescribedVarTemplate(NewTemplate);
7887  }
7888 
7889  // If this decl has an auto type in need of deduction, make a note of the
7890  // Decl so we can diagnose uses of it in its own initializer.
7891  if (R->getContainedDeducedType())
7892  ParsingInitForAutoVars.insert(NewVD);
7893 
7894  if (D.isInvalidType() || Invalid) {
7895  NewVD->setInvalidDecl();
7896  if (NewTemplate)
7897  NewTemplate->setInvalidDecl();
7898  }
7899 
7900  SetNestedNameSpecifier(*this, NewVD, D);
7901 
7902  // If we have any template parameter lists that don't directly belong to
7903  // the variable (matching the scope specifier), store them.
7904  // An explicit variable template specialization does not own any template
7905  // parameter lists.
7906  bool IsExplicitSpecialization =
7907  IsVariableTemplateSpecialization && !IsPartialSpecialization;
7908  unsigned VDTemplateParamLists =
7909  (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7910  if (TemplateParamLists.size() > VDTemplateParamLists)
7912  Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7913  }
7914 
7915  if (D.getDeclSpec().isInlineSpecified()) {
7916  if (!getLangOpts().CPlusPlus) {
7917  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7918  << 0;
7919  } else if (CurContext->isFunctionOrMethod()) {
7920  // 'inline' is not allowed on block scope variable declaration.
7922  diag::err_inline_declaration_block_scope) << Name
7924  } else {
7926  getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7927  : diag::ext_inline_variable);
7928  NewVD->setInlineSpecified();
7929  }
7930  }
7931 
7932  // Set the lexical context. If the declarator has a C++ scope specifier, the
7933  // lexical context will be different from the semantic context.
7934  NewVD->setLexicalDeclContext(CurContext);
7935  if (NewTemplate)
7936  NewTemplate->setLexicalDeclContext(CurContext);
7937 
7938  if (IsLocalExternDecl) {
7939  if (D.isDecompositionDeclarator())
7940  for (auto *B : Bindings)
7941  B->setLocalExternDecl();
7942  else
7943  NewVD->setLocalExternDecl();
7944  }
7945 
7946  bool EmitTLSUnsupportedError = false;
7948  // C++11 [dcl.stc]p4:
7949  // When thread_local is applied to a variable of block scope the
7950  // storage-class-specifier static is implied if it does not appear
7951  // explicitly.
7952  // Core issue: 'static' is not implied if the variable is declared
7953  // 'extern'.
7954  if (NewVD->hasLocalStorage() &&
7955  (SCSpec != DeclSpec::SCS_unspecified ||
7956  TSCS != DeclSpec::TSCS_thread_local ||
7957  !DC->isFunctionOrMethod()))
7959  diag::err_thread_non_global)
7960  << DeclSpec::getSpecifierName(TSCS);
7961  else if (!Context.getTargetInfo().isTLSSupported()) {
7962  if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7963  getLangOpts().SYCLIsDevice) {
7964  // Postpone error emission until we've collected attributes required to
7965  // figure out whether it's a host or device variable and whether the
7966  // error should be ignored.
7967  EmitTLSUnsupportedError = true;
7968  // We still need to mark the variable as TLS so it shows up in AST with
7969  // proper storage class for other tools to use even if we're not going
7970  // to emit any code for it.
7971  NewVD->setTSCSpec(TSCS);
7972  } else
7974  diag::err_thread_unsupported);
7975  } else
7976  NewVD->setTSCSpec(TSCS);
7977  }
7978 
7979  if (getLangOpts().SYCLIsDevice) {
7980  // device_global array is not allowed.
7981  if (const ArrayType *AT = getASTContext().getAsArrayType(NewVD->getType()))
7982  if (SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
7983  AT->getElementType()))
7984  Diag(NewVD->getLocation(), diag::err_sycl_device_global_array);
7985 
7986  // Global variables with types decorated with device_global attribute must
7987  // be static if they are declared in SYCL device code.
7988  if (SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
7989  NewVD->getType())) {
7990  if (SCSpec == DeclSpec::SCS_static) {
7991  const DeclContext *DC = NewVD->getDeclContext();
7992  while (!DC->isTranslationUnit()) {
7993  if (isa<FunctionDecl>(DC)) {
7994  Diag(D.getIdentifierLoc(),
7995  diag::err_sycl_device_global_incorrect_scope);
7996  break;
7997  }
7998  DC = DC->getParent();
7999  }
8000  } else if (!NewVD->hasGlobalStorage()) {
8001  Diag(D.getIdentifierLoc(),
8002  diag::err_sycl_device_global_incorrect_scope);
8003  }
8004  }
8005 
8006  // Static variables declared inside SYCL device code must be const or
8007  // constexpr unless their types are decorated with global_variable_allowed
8008  // attribute.
8009  if (SCSpec == DeclSpec::SCS_static && !R.isConstant(Context) &&
8010  !SYCL().isTypeDecoratedWithDeclAttribute<SYCLGlobalVariableAllowedAttr>(
8011  NewVD->getType()))
8012  SYCL().DiagIfDeviceCode(D.getIdentifierLoc(), diag::err_sycl_restrict)
8014  }
8015 
8016  switch (D.getDeclSpec().getConstexprSpecifier()) {
8018  break;
8019 
8022  diag::err_constexpr_wrong_decl_kind)
8023  << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8024  [[fallthrough]];
8025 
8027  NewVD->setConstexpr(true);
8028  // C++1z [dcl.spec.constexpr]p1:
8029  // A static data member declared with the constexpr specifier is
8030  // implicitly an inline variable.
8031  if (NewVD->isStaticDataMember() &&
8032  (getLangOpts().CPlusPlus17 ||
8033  Context.getTargetInfo().getCXXABI().isMicrosoft()))
8034  NewVD->setImplicitlyInline();
8035  break;
8036 
8038  if (!NewVD->hasGlobalStorage())
8040  diag::err_constinit_local_variable);
8041  else
8042  NewVD->addAttr(
8043  ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8044  ConstInitAttr::Keyword_constinit));
8045  break;
8046  }
8047 
8048  // C99 6.7.4p3
8049  // An inline definition of a function with external linkage shall
8050  // not contain a definition of a modifiable object with static or
8051  // thread storage duration...
8052  // We only apply this when the function is required to be defined
8053  // elsewhere, i.e. when the function is not 'extern inline'. Note
8054  // that a local variable with thread storage duration still has to
8055  // be marked 'static'. Also note that it's possible to get these
8056  // semantics in C++ using __attribute__((gnu_inline)).
8057  if (SC == SC_Static && S->getFnParent() != nullptr &&
8058  !NewVD->getType().isConstQualified()) {
8059  FunctionDecl *CurFD = getCurFunctionDecl();
8060  if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8062  diag::warn_static_local_in_extern_inline);
8063  MaybeSuggestAddingStaticToDecl(CurFD);
8064  }
8065  }
8066 
8068  if (IsVariableTemplateSpecialization)
8069  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8070  << (IsPartialSpecialization ? 1 : 0)
8073  else if (IsMemberSpecialization)
8074  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8075  << 2
8077  else if (NewVD->hasLocalStorage())
8078  Diag(NewVD->getLocation(), diag::err_module_private_local)
8079  << 0 << NewVD
8083  else {
8084  NewVD->setModulePrivate();
8085  if (NewTemplate)
8086  NewTemplate->setModulePrivate();
8087  for (auto *B : Bindings)
8088  B->setModulePrivate();
8089  }
8090  }
8091 
8092  if (getLangOpts().OpenCL) {
8093  deduceOpenCLAddressSpace(NewVD);
8094 
8096  if (TSC != TSCS_unspecified) {
8098  diag::err_opencl_unknown_type_specifier)
8099  << getLangOpts().getOpenCLVersionString()
8100  << DeclSpec::getSpecifierName(TSC) << 1;
8101  NewVD->setInvalidDecl();
8102  }
8103  }
8104 
8105  // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8106  // address space if the table has local storage (semantic checks elsewhere
8107  // will produce an error anyway).
8108  if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8109  if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8110  !NewVD->hasLocalStorage()) {
8112  NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8113  NewVD->setType(Type);
8114  }
8115  }
8116 
8117  // Handle attributes prior to checking for duplicates in MergeVarDecl
8118  ProcessDeclAttributes(S, NewVD, D);
8119 
8120  // FIXME: This is probably the wrong location to be doing this and we should
8121  // probably be doing this for more attributes (especially for function
8122  // pointer attributes such as format, warn_unused_result, etc.). Ideally
8123  // the code to copy attributes would be generated by TableGen.
8124  if (R->isFunctionPointerType())
8125  if (const auto *TT = R->getAs<TypedefType>())
8126  copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8127 
8128  if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
8129  getLangOpts().SYCLIsDevice) {
8130  if (EmitTLSUnsupportedError &&
8131  ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
8132  (getLangOpts().OpenMPIsTargetDevice &&
8133  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8135  diag::err_thread_unsupported);
8136 
8137  if (EmitTLSUnsupportedError &&
8138  (LangOpts.SYCLIsDevice ||
8139  (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8140  targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8141  // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8142  // storage [duration]."
8143  if (SC == SC_None && S->getFnParent() != nullptr &&
8144  (NewVD->hasAttr<CUDASharedAttr>() ||
8145  NewVD->hasAttr<CUDAConstantAttr>())) {
8146  NewVD->setStorageClass(SC_Static);
8147  }
8148  }
8149 
8150  // Ensure that dllimport globals without explicit storage class are treated as
8151  // extern. The storage class is set above using parsed attributes. Now we can
8152  // check the VarDecl itself.
8153  assert(!NewVD->hasAttr<DLLImportAttr>() ||
8154  NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8155  NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8156 
8157  // In auto-retain/release, infer strong retension for variables of
8158  // retainable type.
8159  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8160  NewVD->setInvalidDecl();
8161 
8162  // Handle GNU asm-label extension (encoded as an attribute).
8163  if (Expr *E = (Expr*)D.getAsmLabel()) {
8164  // The parser guarantees this is a string.
8165  StringLiteral *SE = cast<StringLiteral>(E);
8166  StringRef Label = SE->getString();
8167  if (S->getFnParent() != nullptr) {
8168  switch (SC) {
8169  case SC_None:
8170  case SC_Auto:
8171  Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8172  break;
8173  case SC_Register:
8174  // Local Named register
8175  if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8176  DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) {
8177  if (getLangOpts().SYCLIsDevice)
8178  SYCL().DiagIfDeviceCode(E->getExprLoc(),
8179  diag::err_asm_unknown_register_name)
8180  << Label;
8181  else
8182  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8183  }
8184  break;
8185  case SC_Static:
8186  case SC_Extern:
8187  case SC_PrivateExtern:
8188  break;
8189  }
8190  } else if (SC == SC_Register) {
8191  // Global Named register
8192  if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8193  const auto &TI = Context.getTargetInfo();
8194  bool HasSizeMismatch;
8195 
8196  if (!TI.isValidGCCRegisterName(Label))
8197  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8198  else if (!TI.validateGlobalRegisterVariable(Label,
8199  Context.getTypeSize(R),
8200  HasSizeMismatch))
8201  Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8202  else if (HasSizeMismatch)
8203  Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8204  }
8205 
8206  if (!R->isIntegralType(Context) && !R->isPointerType()) {
8207  Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8208  NewVD->setInvalidDecl(true);
8209  }
8210  }
8211 
8212  NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8213  /*IsLiteralLabel=*/true,
8214  SE->getStrTokenLoc(0)));
8215  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8216  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8217  ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8218  if (I != ExtnameUndeclaredIdentifiers.end()) {
8219  if (isDeclExternC(NewVD)) {
8220  NewVD->addAttr(I->second);
8221  ExtnameUndeclaredIdentifiers.erase(I);
8222  } else
8223  Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8224  << /*Variable*/1 << NewVD;
8225  }
8226  }
8227 
8228  // Find the shadowed declaration before filtering for scope.
8229  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8230  ? getShadowedDeclaration(NewVD, Previous)
8231  : nullptr;
8232 
8233  // Don't consider existing declarations that are in a different
8234  // scope and are out-of-semantic-context declarations (if the new
8235  // declaration has linkage).
8236  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8237  D.getCXXScopeSpec().isNotEmpty() ||
8238  IsMemberSpecialization ||
8239  IsVariableTemplateSpecialization);
8240 
8241  // Check whether the previous declaration is in the same block scope. This
8242  // affects whether we merge types with it, per C++11 [dcl.array]p3.
8243  if (getLangOpts().CPlusPlus &&
8244  NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8246  Previous.isSingleResult() && !Previous.isShadowed() &&
8247  isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8248 
8249  if (!getLangOpts().CPlusPlus) {
8250  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8251  } else {
8252  // If this is an explicit specialization of a static data member, check it.
8253  if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
8254  !NewVD->isInvalidDecl() && CheckMemberSpecialization(NewVD, Previous))
8255  NewVD->setInvalidDecl();
8256 
8257  // Merge the decl with the existing one if appropriate.
8258  if (!Previous.empty()) {
8259  if (Previous.isSingleResult() &&
8260  isa<FieldDecl>(Previous.getFoundDecl()) &&
8261  D.getCXXScopeSpec().isSet()) {
8262  // The user tried to define a non-static data member
8263  // out-of-line (C++ [dcl.meaning]p1).
8264  Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8265  << D.getCXXScopeSpec().getRange();
8266  Previous.clear();
8267  NewVD->setInvalidDecl();
8268  }
8269  } else if (D.getCXXScopeSpec().isSet() &&
8270  !IsVariableTemplateSpecialization) {
8271  // No previous declaration in the qualifying scope.
8272  Diag(D.getIdentifierLoc(), diag::err_no_member)
8273  << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8274  << D.getCXXScopeSpec().getRange();
8275  NewVD->setInvalidDecl();
8276  }
8277 
8278  if (!IsPlaceholderVariable)
8279  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8280 
8281  // CheckVariableDeclaration will set NewVD as invalid if something is in
8282  // error like WebAssembly tables being declared as arrays with a non-zero
8283  // size, but then parsing continues and emits further errors on that line.
8284  // To avoid that we check here if it happened and return nullptr.
8285  if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8286  return nullptr;
8287 
8288  if (NewTemplate) {
8289  VarTemplateDecl *PrevVarTemplate =
8290  NewVD->getPreviousDecl()
8292  : nullptr;
8293 
8294  // Check the template parameter list of this declaration, possibly
8295  // merging in the template parameter list from the previous variable
8296  // template declaration.
8297  if (CheckTemplateParameterList(
8298  TemplateParams,
8299  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8300  : nullptr,
8301  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8302  DC->isDependentContext())
8303  ? TPC_ClassTemplateMember
8304  : TPC_VarTemplate))
8305  NewVD->setInvalidDecl();
8306 
8307  // If we are providing an explicit specialization of a static variable
8308  // template, make a note of that.
8309  if (PrevVarTemplate &&
8310  PrevVarTemplate->getInstantiatedFromMemberTemplate())
8311  PrevVarTemplate->setMemberSpecialization();
8312  }
8313  }
8314 
8315  // Diagnose shadowed variables iff this isn't a redeclaration.
8316  if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8317  CheckShadow(NewVD, ShadowedDecl, Previous);
8318 
8319  ProcessPragmaWeak(S, NewVD);
8320 
8321  // If this is the first declaration of an extern C variable, update
8322  // the map of such variables.
8323  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8324  isIncompleteDeclExternC(*this, NewVD))
8325  RegisterLocallyScopedExternCDecl(NewVD, S);
8326 
8327  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8328  MangleNumberingContext *MCtx;
8329  Decl *ManglingContextDecl;
8330  std::tie(MCtx, ManglingContextDecl) =
8331  getCurrentMangleNumberContext(NewVD->getDeclContext());
8332  if (MCtx) {
8333  Context.setManglingNumber(
8334  NewVD, MCtx->getManglingNumber(
8335  NewVD, getMSManglingNumber(getLangOpts(), S)));
8336  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8337  }
8338  }
8339 
8340  // Special handling of variable named 'main'.
8341  if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8343  !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8344 
8345  // C++ [basic.start.main]p3
8346  // A program that declares a variable main at global scope is ill-formed.
8347  if (getLangOpts().CPlusPlus)
8348  Diag(D.getBeginLoc(), diag::err_main_global_variable);
8349 
8350  // In C, and external-linkage variable named main results in undefined
8351  // behavior.
8352  else if (NewVD->hasExternalFormalLinkage())
8353  Diag(D.getBeginLoc(), diag::warn_main_redefined);
8354  }
8355 
8356  if (D.isRedeclaration() && !Previous.empty()) {
8357  NamedDecl *Prev = Previous.getRepresentativeDecl();
8358  checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8359  D.isFunctionDefinition());
8360  }
8361 
8362  if (NewTemplate) {
8363  if (NewVD->isInvalidDecl())
8364  NewTemplate->setInvalidDecl();
8365  ActOnDocumentableDecl(NewTemplate);
8366  return NewTemplate;
8367  }
8368 
8369  if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8370  CompleteMemberSpecialization(NewVD, Previous);
8371 
8372  SYCL().addSyclVarDecl(NewVD);
8373  emitReadOnlyPlacementAttrWarning(*this, NewVD);
8374 
8375  return NewVD;
8376 }
8377 
8378 /// Enum describing the %select options in diag::warn_decl_shadow.
8387 };
8388 
8389 /// Determine what kind of declaration we're shadowing.
8391  const DeclContext *OldDC) {
8392  if (isa<TypeAliasDecl>(ShadowedDecl))
8393  return SDK_Using;
8394  else if (isa<TypedefDecl>(ShadowedDecl))
8395  return SDK_Typedef;
8396  else if (isa<BindingDecl>(ShadowedDecl))
8397  return SDK_StructuredBinding;
8398  else if (isa<RecordDecl>(OldDC))
8399  return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8400 
8401  return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8402 }
8403 
8404 /// Return the location of the capture if the given lambda captures the given
8405 /// variable \p VD, or an invalid source location otherwise.
8407  const VarDecl *VD) {
8408  for (const Capture &Capture : LSI->Captures) {
8409  if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8410  return Capture.getLocation();
8411  }
8412  return SourceLocation();
8413 }
8414 
8416  const LookupResult &R) {
8417  // Only diagnose if we're shadowing an unambiguous field or variable.
8419  return false;
8420 
8421  // Return false if warning is ignored.
8422  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8423 }
8424 
8425 /// Return the declaration shadowed by the given variable \p D, or null
8426 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8428  const LookupResult &R) {
8429  if (!shouldWarnIfShadowedDecl(Diags, R))
8430  return nullptr;
8431 
8432  // Don't diagnose declarations at file scope.
8433  if (D->hasGlobalStorage() && !D->isStaticLocal())
8434  return nullptr;
8435 
8436  NamedDecl *ShadowedDecl = R.getFoundDecl();
8437  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8438  : nullptr;
8439 }
8440 
8441 /// Return the declaration shadowed by the given typedef \p D, or null
8442 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8444  const LookupResult &R) {
8445  // Don't warn if typedef declaration is part of a class
8446  if (D->getDeclContext()->isRecord())
8447  return nullptr;
8448 
8449  if (!shouldWarnIfShadowedDecl(Diags, R))
8450  return nullptr;
8451 
8452  NamedDecl *ShadowedDecl = R.getFoundDecl();
8453  return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8454 }
8455 
8456 /// Return the declaration shadowed by the given variable \p D, or null
8457 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8459  const LookupResult &R) {
8460  if (!shouldWarnIfShadowedDecl(Diags, R))
8461  return nullptr;
8462 
8463  NamedDecl *ShadowedDecl = R.getFoundDecl();
8464  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8465  : nullptr;
8466 }
8467 
8468 /// Diagnose variable or built-in function shadowing. Implements
8469 /// -Wshadow.
8470 ///
8471 /// This method is called whenever a VarDecl is added to a "useful"
8472 /// scope.
8473 ///
8474 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8475 /// \param R the lookup of the name
8476 ///
8477 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8478  const LookupResult &R) {
8479  DeclContext *NewDC = D->getDeclContext();
8480 
8481  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8482  // Fields are not shadowed by variables in C++ static methods.
8483  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8484  if (MD->isStatic())
8485  return;
8486 
8487  // Fields shadowed by constructor parameters are a special case. Usually
8488  // the constructor initializes the field with the parameter.
8489  if (isa<CXXConstructorDecl>(NewDC))
8490  if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8491  // Remember that this was shadowed so we can either warn about its
8492  // modification or its existence depending on warning settings.
8493  ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8494  return;
8495  }
8496  }
8497 
8498  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8499  if (shadowedVar->isExternC()) {
8500  // For shadowing external vars, make sure that we point to the global
8501  // declaration, not a locally scoped extern declaration.
8502  for (auto *I : shadowedVar->redecls())
8503  if (I->isFileVarDecl()) {
8504  ShadowedDecl = I;
8505  break;
8506  }
8507  }
8508 
8509  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8510 
8511  unsigned WarningDiag = diag::warn_decl_shadow;
8512  SourceLocation CaptureLoc;
8513  if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8514  if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8515  if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8516  if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8517  const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8518  if (RD->getLambdaCaptureDefault() == LCD_None) {
8519  // Try to avoid warnings for lambdas with an explicit capture
8520  // list. Warn only when the lambda captures the shadowed decl
8521  // explicitly.
8522  CaptureLoc = getCaptureLocation(LSI, VD);
8523  if (CaptureLoc.isInvalid())
8524  WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8525  } else {
8526  // Remember that this was shadowed so we can avoid the warning if
8527  // the shadowed decl isn't captured and the warning settings allow
8528  // it.
8529  cast<LambdaScopeInfo>(getCurFunction())
8530  ->ShadowingDecls.push_back({D, VD});
8531  return;
8532  }
8533  }
8534  if (isa<FieldDecl>(ShadowedDecl)) {
8535  // If lambda can capture this, then emit default shadowing warning,
8536  // Otherwise it is not really a shadowing case since field is not
8537  // available in lambda's body.
8538  // At this point we don't know that lambda can capture this, so
8539  // remember that this was shadowed and delay until we know.
8540  cast<LambdaScopeInfo>(getCurFunction())
8541  ->ShadowingDecls.push_back({D, ShadowedDecl});
8542  return;
8543  }
8544  }
8545  if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8546  VD && VD->hasLocalStorage()) {
8547  // A variable can't shadow a local variable in an enclosing scope, if
8548  // they are separated by a non-capturing declaration context.
8549  for (DeclContext *ParentDC = NewDC;
8550  ParentDC && !ParentDC->Equals(OldDC);
8551  ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8552  // Only block literals, captured statements, and lambda expressions
8553  // can capture; other scopes don't.
8554  if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8555  !isLambdaCallOperator(ParentDC)) {
8556  return;
8557  }
8558  }
8559  }
8560  }
8561  }
8562 
8563  // Never warn about shadowing a placeholder variable.
8564  if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8565  return;
8566 
8567  // Only warn about certain kinds of shadowing for class members.
8568  if (NewDC && NewDC->isRecord()) {
8569  // In particular, don't warn about shadowing non-class members.
8570  if (!OldDC->isRecord())
8571  return;
8572 
8573  // TODO: should we warn about static data members shadowing
8574  // static data members from base classes?
8575 
8576  // TODO: don't diagnose for inaccessible shadowed members.
8577  // This is hard to do perfectly because we might friend the
8578  // shadowing context, but that's just a false negative.
8579  }
8580 
8581 
8582  DeclarationName Name = R.getLookupName();
8583 
8584  // Emit warning and note.
8585  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8586  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8587  if (!CaptureLoc.isInvalid())
8588  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8589  << Name << /*explicitly*/ 1;
8590  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8591 }
8592 
8593 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8594 /// when these variables are captured by the lambda.
8596  for (const auto &Shadow : LSI->ShadowingDecls) {
8597  const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8598  // Try to avoid the warning when the shadowed decl isn't captured.
8599  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8600  if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8601  SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8602  Diag(Shadow.VD->getLocation(),
8603  CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8604  : diag::warn_decl_shadow)
8605  << Shadow.VD->getDeclName()
8606  << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8607  if (CaptureLoc.isValid())
8608  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8609  << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8610  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8611  } else if (isa<FieldDecl>(ShadowedDecl)) {
8612  Diag(Shadow.VD->getLocation(),
8613  LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8614  : diag::warn_decl_shadow_uncaptured_local)
8615  << Shadow.VD->getDeclName()
8616  << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8617  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8618  }
8619  }
8620 }
8621 
8622 /// Check -Wshadow without the advantage of a previous lookup.
8624  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8625  return;
8626 
8627  LookupResult R(*this, D->getDeclName(), D->getLocation(),
8630  LookupName(R, S);
8631  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8632  CheckShadow(D, ShadowedDecl, R);
8633 }
8634 
8635 /// Check if 'E', which is an expression that is about to be modified, refers
8636 /// to a constructor parameter that shadows a field.
8638  // Quickly ignore expressions that can't be shadowing ctor parameters.
8639  if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8640  return;
8641  E = E->IgnoreParenImpCasts();
8642  auto *DRE = dyn_cast<DeclRefExpr>(E);
8643  if (!DRE)
8644  return;
8645  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8646  auto I = ShadowingDecls.find(D);
8647  if (I == ShadowingDecls.end())
8648  return;
8649  const NamedDecl *ShadowedDecl = I->second;
8650  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8651  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8652  Diag(D->getLocation(), diag::note_var_declared_here) << D;
8653  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8654 
8655  // Avoid issuing multiple warnings about the same decl.
8656  ShadowingDecls.erase(I);
8657 }
8658 
8659 /// Check for conflict between this global or extern "C" declaration and
8660 /// previous global or extern "C" declarations. This is only used in C++.
8661 template<typename T>
8663  Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8664  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8665  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8666 
8667  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8668  // The common case: this global doesn't conflict with any extern "C"
8669  // declaration.
8670  return false;
8671  }
8672 
8673  if (Prev) {
8674  if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8675  // Both the old and new declarations have C language linkage. This is a
8676  // redeclaration.
8677  Previous.clear();
8678  Previous.addDecl(Prev);
8679  return true;
8680  }
8681 
8682  // This is a global, non-extern "C" declaration, and there is a previous
8683  // non-global extern "C" declaration. Diagnose if this is a variable
8684  // declaration.
8685  if (!isa<VarDecl>(ND))
8686  return false;
8687  } else {
8688  // The declaration is extern "C". Check for any declaration in the
8689  // translation unit which might conflict.
8690  if (IsGlobal) {
8691  // We have already performed the lookup into the translation unit.
8692  IsGlobal = false;
8693  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8694  I != E; ++I) {
8695  if (isa<VarDecl>(*I)) {
8696  Prev = *I;
8697  break;
8698  }
8699  }
8700  } else {
8702  S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8703  for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8704  I != E; ++I) {
8705  if (isa<VarDecl>(*I)) {
8706  Prev = *I;
8707  break;
8708  }
8709  // FIXME: If we have any other entity with this name in global scope,
8710  // the declaration is ill-formed, but that is a defect: it breaks the
8711  // 'stat' hack, for instance. Only variables can have mangled name
8712  // clashes with extern "C" declarations, so only they deserve a
8713  // diagnostic.
8714  }
8715  }
8716 
8717  if (!Prev)
8718  return false;
8719  }
8720 
8721  // Use the first declaration's location to ensure we point at something which
8722  // is lexically inside an extern "C" linkage-spec.
8723  assert(Prev && "should have found a previous declaration to diagnose");
8724  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8725  Prev = FD->getFirstDecl();
8726  else
8727  Prev = cast<VarDecl>(Prev)->getFirstDecl();
8728 
8729  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8730  << IsGlobal << ND;
8731  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8732  << IsGlobal;
8733  return false;
8734 }
8735 
8736 /// Apply special rules for handling extern "C" declarations. Returns \c true
8737 /// if we have found that this is a redeclaration of some prior entity.
8738 ///
8739 /// Per C++ [dcl.link]p6:
8740 /// Two declarations [for a function or variable] with C language linkage
8741 /// with the same name that appear in different scopes refer to the same
8742 /// [entity]. An entity with C language linkage shall not be declared with
8743 /// the same name as an entity in global scope.
8744 template<typename T>
8747  if (!S.getLangOpts().CPlusPlus) {
8748  // In C, when declaring a global variable, look for a corresponding 'extern'
8749  // variable declared in function scope. We don't need this in C++, because
8750  // we find local extern decls in the surrounding file-scope DeclContext.
8751  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8752  if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8753  Previous.clear();
8754  Previous.addDecl(Prev);
8755  return true;
8756  }
8757  }
8758  return false;
8759  }
8760 
8761  // A declaration in the translation unit can conflict with an extern "C"
8762  // declaration.
8763  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8764  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8765 
8766  // An extern "C" declaration can conflict with a declaration in the
8767  // translation unit or can be a redeclaration of an extern "C" declaration
8768  // in another scope.
8769  if (isIncompleteDeclExternC(S,ND))
8770  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8771 
8772  // Neither global nor extern "C": nothing to do.
8773  return false;
8774 }
8775 
8776 static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8777  QualType T) {
8778  QualType CanonT = SemaRef.Context.getCanonicalType(T);
8779  // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8780  // any of its members, even recursively, shall not have an atomic type, or a
8781  // variably modified type, or a type that is volatile or restrict qualified.
8782  if (CanonT->isVariablyModifiedType()) {
8783  SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8784  return true;
8785  }
8786 
8787  // Arrays are qualified by their element type, so get the base type (this
8788  // works on non-arrays as well).
8789  CanonT = SemaRef.Context.getBaseElementType(CanonT);
8790 
8791  if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8792  CanonT.isRestrictQualified()) {
8793  SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8794  return true;
8795  }
8796 
8797  if (CanonT->isRecordType()) {
8798  const RecordDecl *RD = CanonT->getAsRecordDecl();
8799  if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8800  return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8801  }))
8802  return true;
8803  }
8804 
8805  return false;
8806 }
8807 
8809  // If the decl is already known invalid, don't check it.
8810  if (NewVD->isInvalidDecl())
8811  return;
8812 
8813  QualType T = NewVD->getType();
8814 
8815  // Defer checking an 'auto' type until its initializer is attached.
8816  if (T->isUndeducedType())
8817  return;
8818 
8819  if (NewVD->hasAttrs())
8820  CheckAlignasUnderalignment(NewVD);
8821 
8822  if (T->isObjCObjectType()) {
8823  Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8824  << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8825  T = Context.getObjCObjectPointerType(T);
8826  NewVD->setType(T);
8827  }
8828 
8829  // Emit an error if an address space was applied to decl with local storage.
8830  // This includes arrays of objects with address space qualifiers, but not
8831  // automatic variables that point to other address spaces.
8832  // ISO/IEC TR 18037 S5.1.2
8833  if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8834  T.getAddressSpace() != LangAS::Default) {
8835  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8836  NewVD->setInvalidDecl();
8837  return;
8838  }
8839 
8840  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8841  // scope.
8842  if (getLangOpts().OpenCLVersion == 120 &&
8843  !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8844  getLangOpts()) &&
8845  NewVD->isStaticLocal()) {
8846  Diag(NewVD->getLocation(), diag::err_static_function_scope);
8847  NewVD->setInvalidDecl();
8848  return;
8849  }
8850 
8851  if (getLangOpts().OpenCL) {
8852  if (!diagnoseOpenCLTypes(*this, NewVD))
8853  return;
8854 
8855  // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8856  if (NewVD->hasAttr<BlocksAttr>()) {
8857  Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8858  return;
8859  }
8860 
8861  if (T->isBlockPointerType()) {
8862  // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8863  // can't use 'extern' storage class.
8864  if (!T.isConstQualified()) {
8865  Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8866  << 0 /*const*/;
8867  NewVD->setInvalidDecl();
8868  return;
8869  }
8870  if (NewVD->hasExternalStorage()) {
8871  Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8872  NewVD->setInvalidDecl();
8873  return;
8874  }
8875  }
8876 
8877  // FIXME: Adding local AS in C++ for OpenCL might make sense.
8878  if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8879  NewVD->hasExternalStorage()) {
8880  if (!T->isSamplerT() && !T->isDependentType() &&
8881  !(T.getAddressSpace() == LangAS::opencl_constant ||
8882  (T.getAddressSpace() == LangAS::opencl_global &&
8883  getOpenCLOptions().areProgramScopeVariablesSupported(
8884  getLangOpts())))) {
8885  int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8886  if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8887  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8888  << Scope << "global or constant";
8889  else
8890  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8891  << Scope << "constant";
8892  NewVD->setInvalidDecl();
8893  return;
8894  }
8895  } else {
8896  if (T.getAddressSpace() == LangAS::opencl_global) {
8897  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8898  << 1 /*is any function*/ << "global";
8899  NewVD->setInvalidDecl();
8900  return;
8901  }
8902  if (T.getAddressSpace() == LangAS::opencl_constant ||
8903  T.getAddressSpace() == LangAS::opencl_local) {
8904  FunctionDecl *FD = getCurFunctionDecl();
8905  // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8906  // in functions.
8907  if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8908  if (T.getAddressSpace() == LangAS::opencl_constant)
8909  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8910  << 0 /*non-kernel only*/ << "constant";
8911  else
8912  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8913  << 0 /*non-kernel only*/ << "local";
8914  NewVD->setInvalidDecl();
8915  return;
8916  }
8917  // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8918  // in the outermost scope of a kernel function.
8919  if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8920  if (!getCurScope()->isFunctionScope()) {
8921  if (T.getAddressSpace() == LangAS::opencl_constant)
8922  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8923  << "constant";
8924  else
8925  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8926  << "local";
8927  NewVD->setInvalidDecl();
8928  return;
8929  }
8930  }
8931  } else if (T.getAddressSpace() != LangAS::opencl_private &&
8932  // If we are parsing a template we didn't deduce an addr
8933  // space yet.
8934  T.getAddressSpace() != LangAS::Default) {
8935  // Do not allow other address spaces on automatic variable.
8936  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8937  NewVD->setInvalidDecl();
8938  return;
8939  }
8940  }
8941  }
8942 
8943  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8944  && !NewVD->hasAttr<BlocksAttr>()) {
8945  if (getLangOpts().getGC() != LangOptions::NonGC)
8946  Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8947  else {
8948  assert(!getLangOpts().ObjCAutoRefCount);
8949  Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8950  }
8951  }
8952 
8953  // WebAssembly tables must be static with a zero length and can't be
8954  // declared within functions.
8955  if (T->isWebAssemblyTableType()) {
8956  if (getCurScope()->getParent()) { // Parent is null at top-level
8957  Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8958  NewVD->setInvalidDecl();
8959  return;
8960  }
8961  if (NewVD->getStorageClass() != SC_Static) {
8962  Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8963  NewVD->setInvalidDecl();
8964  return;
8965  }
8966  const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8967  if (!ATy || ATy->getZExtSize() != 0) {
8968  Diag(NewVD->getLocation(),
8969  diag::err_typecheck_wasm_table_must_have_zero_length);
8970  NewVD->setInvalidDecl();
8971  return;
8972  }
8973  }
8974 
8975  bool isVM = T->isVariablyModifiedType();
8976  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8977  NewVD->hasAttr<BlocksAttr>())
8978  setFunctionHasBranchProtectedScope();
8979 
8980  if ((isVM && NewVD->hasLinkage()) ||
8981  (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8982  bool SizeIsNegative;
8983  llvm::APSInt Oversized;
8985  NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8986  QualType FixedT;
8987  if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8988  FixedT = FixedTInfo->getType();
8989  else if (FixedTInfo) {
8990  // Type and type-as-written are canonically different. We need to fix up
8991  // both types separately.
8992  FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8993  Oversized);
8994  }
8995  if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8996  const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8997  // FIXME: This won't give the correct result for
8998  // int a[10][n];
8999  SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9000 
9001  if (NewVD->isFileVarDecl())
9002  Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9003  << SizeRange;
9004  else if (NewVD->isStaticLocal())
9005  Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9006  << SizeRange;
9007  else
9008  Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9009  << SizeRange;
9010  NewVD->setInvalidDecl();
9011  return;
9012  }
9013 
9014  if (!FixedTInfo) {
9015  if (NewVD->isFileVarDecl())
9016  Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9017  else
9018  Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9019  NewVD->setInvalidDecl();
9020  return;
9021  }
9022 
9023  Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9024  NewVD->setType(FixedT);
9025  NewVD->setTypeSourceInfo(FixedTInfo);
9026  }
9027 
9028  if (T->isVoidType()) {
9029  // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9030  // of objects and functions.
9031  if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9032  Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9033  << T;
9034  NewVD->setInvalidDecl();
9035  return;
9036  }
9037  }
9038 
9039  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9040  Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9041  NewVD->setInvalidDecl();
9042  return;
9043  }
9044 
9045  if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9046  !T.isWebAssemblyReferenceType()) {
9047  Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9048  NewVD->setInvalidDecl();
9049  return;
9050  }
9051 
9052  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9053  Diag(NewVD->getLocation(), diag::err_block_on_vm);
9054  NewVD->setInvalidDecl();
9055  return;
9056  }
9057 
9058  if (getLangOpts().C23 && NewVD->isConstexpr() &&
9059  CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9060  NewVD->setInvalidDecl();
9061  return;
9062  }
9063 
9064  if (NewVD->isConstexpr() && !T->isDependentType() &&
9065  RequireLiteralType(NewVD->getLocation(), T,
9066  diag::err_constexpr_var_non_literal)) {
9067  NewVD->setInvalidDecl();
9068  return;
9069  }
9070 
9071  // PPC MMA non-pointer types are not allowed as non-local variable types.
9072  if (Context.getTargetInfo().getTriple().isPPC64() &&
9073  !NewVD->isLocalVarDecl() &&
9074  CheckPPCMMAType(T, NewVD->getLocation())) {
9075  NewVD->setInvalidDecl();
9076  return;
9077  }
9078 
9079  // Check that SVE types are only used in functions with SVE available.
9080  if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9081  const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
9082  llvm::StringMap<bool> CallerFeatureMap;
9083  Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9085  "sve", CallerFeatureMap)) {
9086  Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
9087  NewVD->setInvalidDecl();
9088  return;
9089  }
9090  }
9091 
9092  if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9093  const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
9094  llvm::StringMap<bool> CallerFeatureMap;
9095  Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9096  checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
9097  CallerFeatureMap);
9098  }
9099 }
9100 
9101 /// Perform semantic checking on a newly-created variable
9102 /// declaration.
9103 ///
9104 /// This routine performs all of the type-checking required for a
9105 /// variable declaration once it has been built. It is used both to
9106 /// check variables after they have been parsed and their declarators
9107 /// have been translated into a declaration, and to check variables
9108 /// that have been instantiated from a template.
9109 ///
9110 /// Sets NewVD->isInvalidDecl() if an error was encountered.
9111 ///
9112 /// Returns true if the variable declaration is a redeclaration.
9114  CheckVariableDeclarationType(NewVD);
9115 
9116  // If the decl is already known invalid, don't check it.
9117  if (NewVD->isInvalidDecl())
9118  return false;
9119 
9120  // If we did not find anything by this name, look for a non-visible
9121  // extern "C" declaration with the same name.
9122  if (Previous.empty() &&
9124  Previous.setShadowed();
9125 
9126  if (!Previous.empty()) {
9127  MergeVarDecl(NewVD, Previous);
9128  return true;
9129  }
9130  return false;
9131 }
9132 
9133 /// AddOverriddenMethods - See if a method overrides any in the base classes,
9134 /// and if so, check that it's a valid override and remember it.
9137 
9138  // Look for methods in base classes that this method might override.
9139  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9140  /*DetectVirtual=*/false);
9141  auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9142  CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9143  DeclarationName Name = MD->getDeclName();
9144 
9145  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9146  // We really want to find the base class destructor here.
9147  QualType T = Context.getTypeDeclType(BaseRecord);
9148  CanQualType CT = Context.getCanonicalType(T);
9149  Name = Context.DeclarationNames.getCXXDestructorName(CT);
9150  }
9151 
9152  for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9153  CXXMethodDecl *BaseMD =
9154  dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9155  if (!BaseMD || !BaseMD->isVirtual() ||
9156  IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9157  /*ConsiderCudaAttrs=*/true))
9158  continue;
9159  if (!CheckExplicitObjectOverride(MD, BaseMD))
9160  continue;
9161  if (Overridden.insert(BaseMD).second) {
9162  MD->addOverriddenMethod(BaseMD);
9163  CheckOverridingFunctionReturnType(MD, BaseMD);
9164  CheckOverridingFunctionAttributes(MD, BaseMD);
9165  CheckOverridingFunctionExceptionSpec(MD, BaseMD);
9166  CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
9167  }
9168 
9169  // A method can only override one function from each base class. We
9170  // don't track indirectly overridden methods from bases of bases.
9171  return true;
9172  }
9173 
9174  return false;
9175  };
9176 
9177  DC->lookupInBases(VisitBase, Paths);
9178  return !Overridden.empty();
9179 }
9180 
9181 namespace {
9182  // Struct for holding all of the extra arguments needed by
9183  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9184  struct ActOnFDArgs {
9185  Scope *S;
9186  Declarator &D;
9187  MultiTemplateParamsArg TemplateParamLists;
9188  bool AddToScope;
9189  };
9190 } // end anonymous namespace
9191 
9192 namespace {
9193 
9194 // Callback to only accept typo corrections that have a non-zero edit distance.
9195 // Also only accept corrections that have the same parent decl.
9196 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9197  public:
9198  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9200  : Context(Context), OriginalFD(TypoFD),
9201  ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9202 
9203  bool ValidateCandidate(const TypoCorrection &candidate) override {
9204  if (candidate.getEditDistance() == 0)
9205  return false;
9206 
9207  SmallVector<unsigned, 1> MismatchedParams;
9208  for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9209  CDeclEnd = candidate.end();
9210  CDecl != CDeclEnd; ++CDecl) {
9211  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9212 
9213  if (FD && !FD->hasBody() &&
9214  hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9215  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9216  CXXRecordDecl *Parent = MD->getParent();
9217  if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9218  return true;
9219  } else if (!ExpectedParent) {
9220  return true;
9221  }
9222  }
9223  }
9224 
9225  return false;
9226  }
9227 
9228  std::unique_ptr<CorrectionCandidateCallback> clone() override {
9229  return std::make_unique<DifferentNameValidatorCCC>(*this);
9230  }
9231 
9232  private:
9233  ASTContext &Context;
9234  FunctionDecl *OriginalFD;
9235  CXXRecordDecl *ExpectedParent;
9236 };
9237 
9238 } // end anonymous namespace
9239 
9241  TypoCorrectedFunctionDefinitions.insert(F);
9242 }
9243 
9244 /// Generate diagnostics for an invalid function redeclaration.
9245 ///
9246 /// This routine handles generating the diagnostic messages for an invalid
9247 /// function redeclaration, including finding possible similar declarations
9248 /// or performing typo correction if there are no previous declarations with
9249 /// the same name.
9250 ///
9251 /// Returns a NamedDecl iff typo correction was performed and substituting in
9252 /// the new declaration name does not cause new errors.
9254  Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9255  ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9256  DeclarationName Name = NewFD->getDeclName();
9257  DeclContext *NewDC = NewFD->getDeclContext();
9258  SmallVector<unsigned, 1> MismatchedParams;
9260  TypoCorrection Correction;
9261  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9262  unsigned DiagMsg =
9263  IsLocalFriend ? diag::err_no_matching_local_friend :
9264  NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9265  diag::err_member_decl_does_not_match;
9266  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9267  IsLocalFriend ? Sema::LookupLocalFriendName
9270 
9271  NewFD->setInvalidDecl();
9272  if (IsLocalFriend)
9273  SemaRef.LookupName(Prev, S);
9274  else
9275  SemaRef.LookupQualifiedName(Prev, NewDC);
9276  assert(!Prev.isAmbiguous() &&
9277  "Cannot have an ambiguity in previous-declaration lookup");
9278  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9279  DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9280  MD ? MD->getParent() : nullptr);
9281  if (!Prev.empty()) {
9282  for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9283  Func != FuncEnd; ++Func) {
9284  FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9285  if (FD &&
9286  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9287  // Add 1 to the index so that 0 can mean the mismatch didn't
9288  // involve a parameter
9289  unsigned ParamNum =
9290  MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9291  NearMatches.push_back(std::make_pair(FD, ParamNum));
9292  }
9293  }
9294  // If the qualified name lookup yielded nothing, try typo correction
9295  } else if ((Correction = SemaRef.CorrectTypo(
9296  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9297  &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9298  IsLocalFriend ? nullptr : NewDC))) {
9299  // Set up everything for the call to ActOnFunctionDeclarator
9300  ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9301  ExtraArgs.D.getIdentifierLoc());
9302  Previous.clear();
9303  Previous.setLookupName(Correction.getCorrection());
9304  for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9305  CDeclEnd = Correction.end();
9306  CDecl != CDeclEnd; ++CDecl) {
9307  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9308  if (FD && !FD->hasBody() &&
9309  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9310  Previous.addDecl(FD);
9311  }
9312  }
9313  bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9314 
9315  NamedDecl *Result;
9316  // Retry building the function declaration with the new previous
9317  // declarations, and with errors suppressed.
9318  {
9319  // Trap errors.
9320  Sema::SFINAETrap Trap(SemaRef);
9321 
9322  // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9323  // pieces need to verify the typo-corrected C++ declaration and hopefully
9324  // eliminate the need for the parameter pack ExtraArgs.
9325  Result = SemaRef.ActOnFunctionDeclarator(
9326  ExtraArgs.S, ExtraArgs.D,
9327  Correction.getCorrectionDecl()->getDeclContext(),
9328  NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9329  ExtraArgs.AddToScope);
9330 
9331  if (Trap.hasErrorOccurred())
9332  Result = nullptr;
9333  }
9334 
9335  if (Result) {
9336  // Determine which correction we picked.
9337  Decl *Canonical = Result->getCanonicalDecl();
9338  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9339  I != E; ++I)
9340  if ((*I)->getCanonicalDecl() == Canonical)
9341  Correction.setCorrectionDecl(*I);
9342 
9343  // Let Sema know about the correction.
9344  SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9345  SemaRef.diagnoseTypo(
9346  Correction,
9347  SemaRef.PDiag(IsLocalFriend
9348  ? diag::err_no_matching_local_friend_suggest
9349  : diag::err_member_decl_does_not_match_suggest)
9350  << Name << NewDC << IsDefinition);
9351  return Result;
9352  }
9353 
9354  // Pretend the typo correction never occurred
9355  ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9356  ExtraArgs.D.getIdentifierLoc());
9357  ExtraArgs.D.setRedeclaration(wasRedeclaration);
9358  Previous.clear();
9359  Previous.setLookupName(Name);
9360  }
9361 
9362  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9363  << Name << NewDC << IsDefinition << NewFD->getLocation();
9364 
9365  bool NewFDisConst = false;
9366  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9367  NewFDisConst = NewMD->isConst();
9368 
9369  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9370  NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9371  NearMatch != NearMatchEnd; ++NearMatch) {
9372  FunctionDecl *FD = NearMatch->first;
9373  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9374  bool FDisConst = MD && MD->isConst();
9375  bool IsMember = MD || !IsLocalFriend;
9376 
9377  // FIXME: These notes are poorly worded for the local friend case.
9378  if (unsigned Idx = NearMatch->second) {
9379  ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9380  SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9381  if (Loc.isInvalid()) Loc = FD->getLocation();
9382  SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9383  : diag::note_local_decl_close_param_match)
9384  << Idx << FDParam->getType()
9385  << NewFD->getParamDecl(Idx - 1)->getType();
9386  } else if (FDisConst != NewFDisConst) {
9387  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9388  << NewFDisConst << FD->getSourceRange().getEnd()
9389  << (NewFDisConst
9390  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9391  .getConstQualifierLoc())
9392  : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9393  .getRParenLoc()
9394  .getLocWithOffset(1),
9395  " const"));
9396  } else
9397  SemaRef.Diag(FD->getLocation(),
9398  IsMember ? diag::note_member_def_close_match
9399  : diag::note_local_decl_close_match);
9400  }
9401  return nullptr;
9402 }
9403 
9405  switch (D.getDeclSpec().getStorageClassSpec()) {
9406  default: llvm_unreachable("Unknown storage class!");
9407  case DeclSpec::SCS_auto:
9409  case DeclSpec::SCS_mutable:
9410  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9411  diag::err_typecheck_sclass_func);
9413  D.setInvalidType();
9414  break;
9415  case DeclSpec::SCS_unspecified: break;
9416  case DeclSpec::SCS_extern:
9418  return SC_None;
9419  return SC_Extern;
9420  case DeclSpec::SCS_static: {
9421  if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9422  // C99 6.7.1p5:
9423  // The declaration of an identifier for a function that has
9424  // block scope shall have no explicit storage-class specifier
9425  // other than extern
9426  // See also (C++ [dcl.stc]p4).
9427  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9428  diag::err_static_block_func);
9429  break;
9430  } else
9431  return SC_Static;
9432  }
9434  }
9435 
9436  // No explicit storage class has already been returned
9437  return SC_None;
9438 }
9439 
9441  DeclContext *DC, QualType &R,
9442  TypeSourceInfo *TInfo,
9443  StorageClass SC,
9444  bool &IsVirtualOkay) {
9445  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9446  DeclarationName Name = NameInfo.getName();
9447 
9448  FunctionDecl *NewFD = nullptr;
9449  bool isInline = D.getDeclSpec().isInlineSpecified();
9450 
9451  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9452  if (ConstexprKind == ConstexprSpecKind::Constinit ||
9453  (SemaRef.getLangOpts().C23 &&
9454  ConstexprKind == ConstexprSpecKind::Constexpr)) {
9455 
9456  if (SemaRef.getLangOpts().C23)
9457  SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9458  diag::err_c23_constexpr_not_variable);
9459  else
9460  SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9461  diag::err_constexpr_wrong_decl_kind)
9462  << static_cast<int>(ConstexprKind);
9463  ConstexprKind = ConstexprSpecKind::Unspecified;
9465  }
9466 
9467  if (!SemaRef.getLangOpts().CPlusPlus) {
9468  // Determine whether the function was written with a prototype. This is
9469  // true when:
9470  // - there is a prototype in the declarator, or
9471  // - the type R of the function is some kind of typedef or other non-
9472  // attributed reference to a type name (which eventually refers to a
9473  // function type). Note, we can't always look at the adjusted type to
9474  // check this case because attributes may cause a non-function
9475  // declarator to still have a function type. e.g.,
9476  // typedef void func(int a);
9477  // __attribute__((noreturn)) func other_func; // This has a prototype
9478  bool HasPrototype =
9480  (D.getDeclSpec().isTypeRep() &&
9481  SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9482  ->isFunctionProtoType()) ||
9484  assert(
9485  (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9486  "Strict prototypes are required");
9487 
9488  NewFD = FunctionDecl::Create(
9489  SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9490  SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9492  /*TrailingRequiresClause=*/nullptr);
9493  if (D.isInvalidType())
9494  NewFD->setInvalidDecl();
9495 
9496  return NewFD;
9497  }
9498 
9500  Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9501 
9502  SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9503 
9504  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9505  // This is a C++ constructor declaration.
9506  assert(DC->isRecord() &&
9507  "Constructors can only be declared in a member context");
9508 
9509  R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9511  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9513  isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9514  InheritedConstructor(), TrailingRequiresClause);
9515 
9516  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9517  // This is a C++ destructor declaration.
9518  if (DC->isRecord()) {
9519  R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9520  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9522  SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9523  SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9524  /*isImplicitlyDeclared=*/false, ConstexprKind,
9525  TrailingRequiresClause);
9526  // User defined destructors start as not selected if the class definition is still
9527  // not done.
9528  if (Record->isBeingDefined())
9529  NewDD->setIneligibleOrNotSelected(true);
9530 
9531  // If the destructor needs an implicit exception specification, set it
9532  // now. FIXME: It'd be nice to be able to create the right type to start
9533  // with, but the type needs to reference the destructor declaration.
9534  if (SemaRef.getLangOpts().CPlusPlus11)
9535  SemaRef.AdjustDestructorExceptionSpec(NewDD);
9536 
9537  IsVirtualOkay = true;
9538  return NewDD;
9539 
9540  } else {
9541  SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9542  D.setInvalidType();
9543 
9544  // Create a FunctionDecl to satisfy the function definition parsing
9545  // code path.
9546  return FunctionDecl::Create(
9547  SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9548  TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9549  /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9550  }
9551 
9552  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9553  if (!DC->isRecord()) {
9554  SemaRef.Diag(D.getIdentifierLoc(),
9555  diag::err_conv_function_not_member);
9556  return nullptr;
9557  }
9558 
9559  SemaRef.CheckConversionDeclarator(D, R, SC);
9560  if (D.isInvalidType())
9561  return nullptr;
9562 
9563  IsVirtualOkay = true;
9565  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9566  TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9567  ExplicitSpecifier, ConstexprKind, SourceLocation(),
9568  TrailingRequiresClause);
9569 
9570  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9571  if (TrailingRequiresClause)
9572  SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9573  diag::err_trailing_requires_clause_on_deduction_guide)
9574  << TrailingRequiresClause->getSourceRange();
9575  if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9576  return nullptr;
9577  return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9578  ExplicitSpecifier, NameInfo, R, TInfo,
9579  D.getEndLoc());
9580  } else if (DC->isRecord()) {
9581  // If the name of the function is the same as the name of the record,
9582  // then this must be an invalid constructor that has a return type.
9583  // (The parser checks for a return type and makes the declarator a
9584  // constructor if it has no return type).
9585  if (Name.getAsIdentifierInfo() &&
9586  Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9587  SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9589  << SourceRange(D.getIdentifierLoc());
9590  return nullptr;
9591  }
9592 
9593  // This is a C++ method declaration.
9595  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9596  TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9597  ConstexprKind, SourceLocation(), TrailingRequiresClause);
9598  IsVirtualOkay = !Ret->isStatic();
9599  return Ret;
9600  } else {
9601  bool isFriend =
9602  SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9603  if (!isFriend && SemaRef.CurContext->isRecord())
9604  return nullptr;
9605 
9606  // Determine whether the function was written with a
9607  // prototype. This true when:
9608  // - we're in C++ (where every function has a prototype),
9609  return FunctionDecl::Create(
9610  SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9611  SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9612  true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9613  }
9614 }
9615 
9623 };
9624 
9626  // Size dependent types are just typedefs to normal integer types
9627  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9628  // integers other than by their names.
9629  StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9630 
9631  // Remove typedefs one by one until we reach a typedef
9632  // for a size dependent type.
9633  QualType DesugaredTy = Ty;
9634  do {
9635  ArrayRef<StringRef> Names(SizeTypeNames);
9636  auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9637  if (Names.end() != Match)
9638  return true;
9639 
9640  Ty = DesugaredTy;
9641  DesugaredTy = Ty.getSingleStepDesugaredType(C);
9642  } while (DesugaredTy != Ty);
9643 
9644  return false;
9645 }
9646 
9648  if (PT->isDependentType())
9649  return InvalidKernelParam;
9650 
9651  if (PT->isPointerType() || PT->isReferenceType()) {
9652  QualType PointeeType = PT->getPointeeType();
9653  if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9654  PointeeType.getAddressSpace() == LangAS::opencl_private ||
9655  PointeeType.getAddressSpace() == LangAS::Default)
9657 
9658  if (PointeeType->isPointerType()) {
9659  // This is a pointer to pointer parameter.
9660  // Recursively check inner type.
9661  OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9662  if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9663  ParamKind == InvalidKernelParam)
9664  return ParamKind;
9665 
9666  // OpenCL v3.0 s6.11.a:
9667  // A restriction to pass pointers to pointers only applies to OpenCL C
9668  // v1.2 or below.
9669  if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9670  return ValidKernelParam;
9671 
9672  return PtrPtrKernelParam;
9673  }
9674 
9675  // C++ for OpenCL v1.0 s2.4:
9676  // Moreover the types used in parameters of the kernel functions must be:
9677  // Standard layout types for pointer parameters. The same applies to
9678  // reference if an implementation supports them in kernel parameters.
9679  if (S.getLangOpts().OpenCLCPlusPlus &&
9681  "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9682  auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9683  bool IsStandardLayoutType = true;
9684  if (CXXRec) {
9685  // If template type is not ODR-used its definition is only available
9686  // in the template definition not its instantiation.
9687  // FIXME: This logic doesn't work for types that depend on template
9688  // parameter (PR58590).
9689  if (!CXXRec->hasDefinition())
9690  CXXRec = CXXRec->getTemplateInstantiationPattern();
9691  if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9692  IsStandardLayoutType = false;
9693  }
9694  if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9695  !IsStandardLayoutType)
9696  return InvalidKernelParam;
9697  }
9698 
9699  // OpenCL v1.2 s6.9.p:
9700  // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9701  if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9702  return ValidKernelParam;
9703 
9704  return PtrKernelParam;
9705  }
9706 
9707  // OpenCL v1.2 s6.9.k:
9708  // Arguments to kernel functions in a program cannot be declared with the
9709  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9710  // uintptr_t or a struct and/or union that contain fields declared to be one
9711  // of these built-in scalar types.
9713  return InvalidKernelParam;
9714 
9715  if (PT->isImageType())
9716  return PtrKernelParam;
9717 
9718  if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9719  return InvalidKernelParam;
9720 
9721  // OpenCL extension spec v1.2 s9.5:
9722  // This extension adds support for half scalar and vector types as built-in
9723  // types that can be used for arithmetic operations, conversions etc.
9724  if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9725  PT->isHalfType())
9726  return InvalidKernelParam;
9727 
9728  // Look into an array argument to check if it has a forbidden type.
9729  if (PT->isArrayType()) {
9730  const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9731  // Call ourself to check an underlying type of an array. Since the
9732  // getPointeeOrArrayElementType returns an innermost type which is not an
9733  // array, this recursive call only happens once.
9734  return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9735  }
9736 
9737  // C++ for OpenCL v1.0 s2.4:
9738  // Moreover the types used in parameters of the kernel functions must be:
9739  // Trivial and standard-layout types C++17 [basic.types] (plain old data
9740  // types) for parameters passed by value;
9741  if (S.getLangOpts().OpenCLCPlusPlus &&
9743  "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9744  !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9745  return InvalidKernelParam;
9746 
9747  if (PT->isRecordType())
9748  return RecordKernelParam;
9749 
9750  return ValidKernelParam;
9751 }
9752 
9754  Sema &S,
9755  Declarator &D,
9756  ParmVarDecl *Param,
9757  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9758  QualType PT = Param->getType();
9759 
9760  // Cache the valid types we encounter to avoid rechecking structs that are
9761  // used again
9762  if (ValidTypes.count(PT.getTypePtr()))
9763  return;
9764 
9765  switch (getOpenCLKernelParameterType(S, PT)) {
9766  case PtrPtrKernelParam:
9767  // OpenCL v3.0 s6.11.a:
9768  // A kernel function argument cannot be declared as a pointer to a pointer
9769  // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9770  S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9771  D.setInvalidType();
9772  return;
9773 
9775  // OpenCL v1.0 s6.5:
9776  // __kernel function arguments declared to be a pointer of a type can point
9777  // to one of the following address spaces only : __global, __local or
9778  // __constant.
9779  S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9780  D.setInvalidType();
9781  return;
9782 
9783  // OpenCL v1.2 s6.9.k:
9784  // Arguments to kernel functions in a program cannot be declared with the
9785  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9786  // uintptr_t or a struct and/or union that contain fields declared to be
9787  // one of these built-in scalar types.
9788 
9789  case InvalidKernelParam:
9790  // OpenCL v1.2 s6.8 n:
9791  // A kernel function argument cannot be declared
9792  // of event_t type.
9793  // Do not diagnose half type since it is diagnosed as invalid argument
9794  // type for any function elsewhere.
9795  if (!PT->isHalfType()) {
9796  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9797 
9798  // Explain what typedefs are involved.
9799  const TypedefType *Typedef = nullptr;
9800  while ((Typedef = PT->getAs<TypedefType>())) {
9801  SourceLocation Loc = Typedef->getDecl()->getLocation();
9802  // SourceLocation may be invalid for a built-in type.
9803  if (Loc.isValid())
9804  S.Diag(Loc, diag::note_entity_declared_at) << PT;
9805  PT = Typedef->desugar();
9806  }
9807  }
9808 
9809  D.setInvalidType();
9810  return;
9811 
9812  case PtrKernelParam:
9813  case ValidKernelParam:
9814  ValidTypes.insert(PT.getTypePtr());
9815  return;
9816 
9817  case RecordKernelParam:
9818  break;
9819  }
9820 
9821  // Track nested structs we will inspect
9822  SmallVector<const Decl *, 4> VisitStack;
9823 
9824  // Track where we are in the nested structs. Items will migrate from
9825  // VisitStack to HistoryStack as we do the DFS for bad field.
9826  SmallVector<const FieldDecl *, 4> HistoryStack;
9827  HistoryStack.push_back(nullptr);
9828 
9829  // At this point we already handled everything except of a RecordType or
9830  // an ArrayType of a RecordType.
9831  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9832  const RecordType *RecTy =
9834  const RecordDecl *OrigRecDecl = RecTy->getDecl();
9835 
9836  VisitStack.push_back(RecTy->getDecl());
9837  assert(VisitStack.back() && "First decl null?");
9838 
9839  do {
9840  const Decl *Next = VisitStack.pop_back_val();
9841  if (!Next) {
9842  assert(!HistoryStack.empty());
9843  // Found a marker, we have gone up a level
9844  if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9845  ValidTypes.insert(Hist->getType().getTypePtr());
9846 
9847  continue;
9848  }
9849 
9850  // Adds everything except the original parameter declaration (which is not a
9851  // field itself) to the history stack.
9852  const RecordDecl *RD;
9853  if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9854  HistoryStack.push_back(Field);
9855 
9856  QualType FieldTy = Field->getType();
9857  // Other field types (known to be valid or invalid) are handled while we
9858  // walk around RecordDecl::fields().
9859  assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9860  "Unexpected type.");
9861  const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9862 
9863  RD = FieldRecTy->castAs<RecordType>()->getDecl();
9864  } else {
9865  RD = cast<RecordDecl>(Next);
9866  }
9867 
9868  // Add a null marker so we know when we've gone back up a level
9869  VisitStack.push_back(nullptr);
9870 
9871  for (const auto *FD : RD->fields()) {
9872  QualType QT = FD->getType();
9873 
9874  if (ValidTypes.count(QT.getTypePtr()))
9875  continue;
9876 
9877  OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9878  if (ParamType == ValidKernelParam)
9879  continue;
9880 
9881  if (ParamType == RecordKernelParam) {
9882  VisitStack.push_back(FD);
9883  continue;
9884  }
9885 
9886  // OpenCL v1.2 s6.9.p:
9887  // Arguments to kernel functions that are declared to be a struct or union
9888  // do not allow OpenCL objects to be passed as elements of the struct or
9889  // union. This restriction was lifted in OpenCL v2.0 with the introduction
9890  // of SVM.
9891  if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9892  ParamType == InvalidAddrSpacePtrKernelParam) {
9893  S.Diag(Param->getLocation(),
9894  diag::err_record_with_pointers_kernel_param)
9895  << PT->isUnionType()
9896  << PT;
9897  } else {
9898  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9899  }
9900 
9901  S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9902  << OrigRecDecl->getDeclName();
9903 
9904  // We have an error, now let's go back up through history and show where
9905  // the offending field came from
9907  I = HistoryStack.begin() + 1,
9908  E = HistoryStack.end();
9909  I != E; ++I) {
9910  const FieldDecl *OuterField = *I;
9911  S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9912  << OuterField->getType();
9913  }
9914 
9915  S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9916  << QT->isPointerType()
9917  << QT;
9918  D.setInvalidType();
9919  return;
9920  }
9921  } while (!VisitStack.empty());
9922 }
9923 
9924 /// Find the DeclContext in which a tag is implicitly declared if we see an
9925 /// elaborated type specifier in the specified context, and lookup finds
9926 /// nothing.
9928  while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9929  DC = DC->getParent();
9930  return DC;
9931 }
9932 
9933 /// Find the Scope in which a tag is implicitly declared if we see an
9934 /// elaborated type specifier in the specified context, and lookup finds
9935 /// nothing.
9936 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9937  while (S->isClassScope() ||
9938  (LangOpts.CPlusPlus &&
9939  S->isFunctionPrototypeScope()) ||
9940  ((S->getFlags() & Scope::DeclScope) == 0) ||
9941  (S->getEntity() && S->getEntity()->isTransparentContext()))
9942  S = S->getParent();
9943  return S;
9944 }
9945 
9946 /// Determine whether a declaration matches a known function in namespace std.
9947 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9948  unsigned BuiltinID) {
9949  switch (BuiltinID) {
9950  case Builtin::BI__GetExceptionInfo:
9951  // No type checking whatsoever.
9952  return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9953 
9954  case Builtin::BIaddressof:
9955  case Builtin::BI__addressof:
9956  case Builtin::BIforward:
9957  case Builtin::BIforward_like:
9958  case Builtin::BImove:
9959  case Builtin::BImove_if_noexcept:
9960  case Builtin::BIas_const: {
9961  // Ensure that we don't treat the algorithm
9962  // OutputIt std::move(InputIt, InputIt, OutputIt)
9963  // as the builtin std::move.
9964  const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9965  return FPT->getNumParams() == 1 && !FPT->isVariadic();
9966  }
9967 
9968  default:
9969  return false;
9970  }
9971 }
9972 
9973 NamedDecl*
9976  MultiTemplateParamsArg TemplateParamListsRef,
9977  bool &AddToScope) {
9978  QualType R = TInfo->getType();
9979 
9980  assert(R->isFunctionType());
9982  Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9983 
9984  SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9985  llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9987  if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9988  Invented->getDepth() == TemplateParamLists.back()->getDepth())
9989  TemplateParamLists.back() = Invented;
9990  else
9991  TemplateParamLists.push_back(Invented);
9992  }
9993 
9994  // TODO: consider using NameInfo for diagnostic.
9995  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9996  DeclarationName Name = NameInfo.getName();
9997  StorageClass SC = getFunctionStorageClass(*this, D);
9998 
10001  diag::err_invalid_thread)
10002  << DeclSpec::getSpecifierName(TSCS);
10003 
10005  adjustMemberFunctionCC(
10007  D.isCtorOrDtor(), D.getIdentifierLoc());
10008 
10009  bool isFriend = false;
10010  FunctionTemplateDecl *FunctionTemplate = nullptr;
10011  bool isMemberSpecialization = false;
10012  bool isFunctionTemplateSpecialization = false;
10013 
10014  bool HasExplicitTemplateArgs = false;
10015  TemplateArgumentListInfo TemplateArgs;
10016 
10017  bool isVirtualOkay = false;
10018 
10019  DeclContext *OriginalDC = DC;
10020  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10021 
10022  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10023  isVirtualOkay);
10024  if (!NewFD) return nullptr;
10025 
10026  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10028 
10029  // Set the lexical context. If this is a function-scope declaration, or has a
10030  // C++ scope specifier, or is the object of a friend declaration, the lexical
10031  // context will be different from the semantic context.
10032  NewFD->setLexicalDeclContext(CurContext);
10033 
10034  if (IsLocalExternDecl)
10035  NewFD->setLocalExternDecl();
10036 
10037  if (getLangOpts().CPlusPlus) {
10038  // The rules for implicit inlines changed in C++20 for methods and friends
10039  // with an in-class definition (when such a definition is not attached to
10040  // the global module). User-specified 'inline' overrides this (set when
10041  // the function decl is created above).
10042  // FIXME: We need a better way to separate C++ standard and clang modules.
10043  bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10044  !NewFD->getOwningModule() ||
10045  NewFD->isFromExplicitGlobalModule() ||
10046  NewFD->getOwningModule()->isHeaderLikeModule();
10047  bool isInline = D.getDeclSpec().isInlineSpecified();
10048  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10049  bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10050  isFriend = D.getDeclSpec().isFriendSpecified();
10051  if (isFriend && !isInline && D.isFunctionDefinition()) {
10052  // Pre-C++20 [class.friend]p5
10053  // A function can be defined in a friend declaration of a
10054  // class . . . . Such a function is implicitly inline.
10055  // Post C++20 [class.friend]p7
10056  // Such a function is implicitly an inline function if it is attached
10057  // to the global module.
10058  NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10059  }
10060 
10061  // If this is a method defined in an __interface, and is not a constructor
10062  // or an overloaded operator, then set the pure flag (isVirtual will already
10063  // return true).
10064  if (const CXXRecordDecl *Parent =
10065  dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10066  if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10067  NewFD->setIsPureVirtual(true);
10068 
10069  // C++ [class.union]p2
10070  // A union can have member functions, but not virtual functions.
10071  if (isVirtual && Parent->isUnion()) {
10072  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10073  NewFD->setInvalidDecl();
10074  }
10075  if ((Parent->isClass() || Parent->isStruct()) &&
10076  Parent->hasAttr<SYCLSpecialClassAttr>() &&
10077  NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10078  NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10079  if (auto *Def = Parent->getDefinition())
10080  Def->setInitMethod(true);
10081  }
10082  }
10083 
10084  SetNestedNameSpecifier(*this, NewFD, D);
10085  isMemberSpecialization = false;
10086  isFunctionTemplateSpecialization = false;
10087  if (D.isInvalidType())
10088  NewFD->setInvalidDecl();
10089 
10090  // Match up the template parameter lists with the scope specifier, then
10091  // determine whether we have a template or a template specialization.
10092  bool Invalid = false;
10093  TemplateIdAnnotation *TemplateId =
10095  ? D.getName().TemplateId
10096  : nullptr;
10097  TemplateParameterList *TemplateParams =
10098  MatchTemplateParametersToScopeSpecifier(
10100  D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10101  isMemberSpecialization, Invalid);
10102  if (TemplateParams) {
10103  // Check that we can declare a template here.
10104  if (CheckTemplateDeclScope(S, TemplateParams))
10105  NewFD->setInvalidDecl();
10106 
10107  if (TemplateParams->size() > 0) {
10108  // This is a function template
10109 
10110  // A destructor cannot be a template.
10111  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10112  Diag(NewFD->getLocation(), diag::err_destructor_template);
10113  NewFD->setInvalidDecl();
10114  // Function template with explicit template arguments.
10115  } else if (TemplateId) {
10116  Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10117  << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10118  NewFD->setInvalidDecl();
10119  }
10120 
10121  // If we're adding a template to a dependent context, we may need to
10122  // rebuilding some of the types used within the template parameter list,
10123  // now that we know what the current instantiation is.
10124  if (DC->isDependentContext()) {
10125  ContextRAII SavedContext(*this, DC);
10126  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
10127  Invalid = true;
10128  }
10129 
10130  FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
10131  NewFD->getLocation(),
10132  Name, TemplateParams,
10133  NewFD);
10134  FunctionTemplate->setLexicalDeclContext(CurContext);
10135  NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10136 
10137  // For source fidelity, store the other template param lists.
10138  if (TemplateParamLists.size() > 1) {
10139  NewFD->setTemplateParameterListsInfo(Context,
10140  ArrayRef<TemplateParameterList *>(TemplateParamLists)
10141  .drop_back(1));
10142  }
10143  } else {
10144  // This is a function template specialization.
10145  isFunctionTemplateSpecialization = true;
10146  // For source fidelity, store all the template param lists.
10147  if (TemplateParamLists.size() > 0)
10148  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10149 
10150  // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10151  if (isFriend) {
10152  // We want to remove the "template<>", found here.
10153  SourceRange RemoveRange = TemplateParams->getSourceRange();
10154 
10155  // If we remove the template<> and the name is not a
10156  // template-id, we're actually silently creating a problem:
10157  // the friend declaration will refer to an untemplated decl,
10158  // and clearly the user wants a template specialization. So
10159  // we need to insert '<>' after the name.
10160  SourceLocation InsertLoc;
10162  InsertLoc = D.getName().getSourceRange().getEnd();
10163  InsertLoc = getLocForEndOfToken(InsertLoc);
10164  }
10165 
10166  Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10167  << Name << RemoveRange
10168  << FixItHint::CreateRemoval(RemoveRange)
10169  << FixItHint::CreateInsertion(InsertLoc, "<>");
10170  Invalid = true;
10171 
10172  // Recover by faking up an empty template argument list.
10173  HasExplicitTemplateArgs = true;
10174  TemplateArgs.setLAngleLoc(InsertLoc);
10175  TemplateArgs.setRAngleLoc(InsertLoc);
10176  }
10177  }
10178  } else {
10179  // Check that we can declare a template here.
10180  if (!TemplateParamLists.empty() && isMemberSpecialization &&
10181  CheckTemplateDeclScope(S, TemplateParamLists.back()))
10182  NewFD->setInvalidDecl();
10183 
10184  // All template param lists were matched against the scope specifier:
10185  // this is NOT (an explicit specialization of) a template.
10186  if (TemplateParamLists.size() > 0)
10187  // For source fidelity, store all the template param lists.
10188  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10189 
10190  // "friend void foo<>(int);" is an implicit specialization decl.
10191  if (isFriend && TemplateId)
10192  isFunctionTemplateSpecialization = true;
10193  }
10194 
10195  // If this is a function template specialization and the unqualified-id of
10196  // the declarator-id is a template-id, convert the template argument list
10197  // into our AST format and check for unexpanded packs.
10198  if (isFunctionTemplateSpecialization && TemplateId) {
10199  HasExplicitTemplateArgs = true;
10200 
10201  TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10202  TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10203  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10204  TemplateId->NumArgs);
10205  translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10206 
10207  // FIXME: Should we check for unexpanded packs if this was an (invalid)
10208  // declaration of a function template partial specialization? Should we
10209  // consider the unexpanded pack context to be a partial specialization?
10210  for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10211  if (DiagnoseUnexpandedParameterPack(
10212  ArgLoc, isFriend ? UPPC_FriendDeclaration
10213  : UPPC_ExplicitSpecialization))
10214  NewFD->setInvalidDecl();
10215  }
10216  }
10217 
10218  if (Invalid) {
10219  NewFD->setInvalidDecl();
10220  if (FunctionTemplate)
10221  FunctionTemplate->setInvalidDecl();
10222  }
10223 
10224  // C++ [dcl.fct.spec]p5:
10225  // The virtual specifier shall only be used in declarations of
10226  // nonstatic class member functions that appear within a
10227  // member-specification of a class declaration; see 10.3.
10228  //
10229  if (isVirtual && !NewFD->isInvalidDecl()) {
10230  if (!isVirtualOkay) {
10232  diag::err_virtual_non_function);
10233  } else if (!CurContext->isRecord()) {
10234  // 'virtual' was specified outside of the class.
10236  diag::err_virtual_out_of_class)
10238  } else if (NewFD->getDescribedFunctionTemplate()) {
10239  // C++ [temp.mem]p3:
10240  // A member function template shall not be virtual.
10242  diag::err_virtual_member_function_template)
10244  } else {
10245  // Okay: Add virtual to the method.
10246  NewFD->setVirtualAsWritten(true);
10247  }
10248 
10249  if (getLangOpts().CPlusPlus14 &&
10250  NewFD->getReturnType()->isUndeducedType())
10251  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10252  }
10253 
10254  // C++ [dcl.fct.spec]p3:
10255  // The inline specifier shall not appear on a block scope function
10256  // declaration.
10257  if (isInline && !NewFD->isInvalidDecl()) {
10258  if (CurContext->isFunctionOrMethod()) {
10259  // 'inline' is not allowed on block scope function declaration.
10261  diag::err_inline_declaration_block_scope) << Name
10263  }
10264  }
10265 
10266  // C++ [dcl.fct.spec]p6:
10267  // The explicit specifier shall be used only in the declaration of a
10268  // constructor or conversion function within its class definition;
10269  // see 12.3.1 and 12.3.2.
10270  if (hasExplicit && !NewFD->isInvalidDecl() &&
10271  !isa<CXXDeductionGuideDecl>(NewFD)) {
10272  if (!CurContext->isRecord()) {
10273  // 'explicit' was specified outside of the class.
10275  diag::err_explicit_out_of_class)
10277  } else if (!isa<CXXConstructorDecl>(NewFD) &&
10278  !isa<CXXConversionDecl>(NewFD)) {
10279  // 'explicit' was specified on a function that wasn't a constructor
10280  // or conversion function.
10282  diag::err_explicit_non_ctor_or_conv_function)
10284  }
10285  }
10286 
10287  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10288  if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10289  // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10290  // are implicitly inline.
10291  NewFD->setImplicitlyInline();
10292 
10293  // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10294  // be either constructors or to return a literal type. Therefore,
10295  // destructors cannot be declared constexpr.
10296  if (isa<CXXDestructorDecl>(NewFD) &&
10297  (!getLangOpts().CPlusPlus20 ||
10298  ConstexprKind == ConstexprSpecKind::Consteval)) {
10299  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10300  << static_cast<int>(ConstexprKind);
10301  NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10304  }
10305  // C++20 [dcl.constexpr]p2: An allocation function, or a
10306  // deallocation function shall not be declared with the consteval
10307  // specifier.
10308  if (ConstexprKind == ConstexprSpecKind::Consteval &&
10309  (NewFD->getOverloadedOperator() == OO_New ||
10310  NewFD->getOverloadedOperator() == OO_Array_New ||
10311  NewFD->getOverloadedOperator() == OO_Delete ||
10312  NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10314  diag::err_invalid_consteval_decl_kind)
10315  << NewFD;
10317  }
10318  }
10319 
10320  // If __module_private__ was specified, mark the function accordingly.
10322  if (isFunctionTemplateSpecialization) {
10323  SourceLocation ModulePrivateLoc
10325  Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10326  << 0
10327  << FixItHint::CreateRemoval(ModulePrivateLoc);
10328  } else {
10329  NewFD->setModulePrivate();
10330  if (FunctionTemplate)
10331  FunctionTemplate->setModulePrivate();
10332  }
10333  }
10334 
10335  if (isFriend) {
10336  if (FunctionTemplate) {
10337  FunctionTemplate->setObjectOfFriendDecl();
10338  FunctionTemplate->setAccess(AS_public);
10339  }
10340  NewFD->setObjectOfFriendDecl();
10341  NewFD->setAccess(AS_public);
10342  }
10343 
10344  // If a function is defined as defaulted or deleted, mark it as such now.
10345  // We'll do the relevant checks on defaulted / deleted functions later.
10346  switch (D.getFunctionDefinitionKind()) {
10349  break;
10350 
10352  NewFD->setDefaulted();
10353  break;
10354 
10356  NewFD->setDeletedAsWritten();
10357  break;
10358  }
10359 
10360  if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10361  D.isFunctionDefinition() && !isInline) {
10362  // Pre C++20 [class.mfct]p2:
10363  // A member function may be defined (8.4) in its class definition, in
10364  // which case it is an inline member function (7.1.2)
10365  // Post C++20 [class.mfct]p1:
10366  // If a member function is attached to the global module and is defined
10367  // in its class definition, it is inline.
10368  NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10369  }
10370 
10371  if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10372  !CurContext->isRecord()) {
10373  // C++ [class.static]p1:
10374  // A data or function member of a class may be declared static
10375  // in a class definition, in which case it is a static member of
10376  // the class.
10377 
10378  // Complain about the 'static' specifier if it's on an out-of-line
10379  // member function definition.
10380 
10381  // MSVC permits the use of a 'static' storage specifier on an out-of-line
10382  // member function template declaration and class member template
10383  // declaration (MSVC versions before 2015), warn about this.
10385  ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10386  cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10387  (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10388  ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10390  }
10391 
10392  // C++11 [except.spec]p15:
10393  // A deallocation function with no exception-specification is treated
10394  // as if it were specified with noexcept(true).
10395  const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10396  if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10397  Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10398  getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10399  NewFD->setType(Context.getFunctionType(
10400  FPT->getReturnType(), FPT->getParamTypes(),
10402 
10403  // C++20 [dcl.inline]/7
10404  // If an inline function or variable that is attached to a named module
10405  // is declared in a definition domain, it shall be defined in that
10406  // domain.
10407  // So, if the current declaration does not have a definition, we must
10408  // check at the end of the TU (or when the PMF starts) to see that we
10409  // have a definition at that point.
10410  if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10411  NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10412  PendingInlineFuncDecls.insert(NewFD);
10413  }
10414  }
10415 
10416  // Filter out previous declarations that don't match the scope.
10417  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10418  D.getCXXScopeSpec().isNotEmpty() ||
10419  isMemberSpecialization ||
10420  isFunctionTemplateSpecialization);
10421 
10422  // Handle GNU asm-label extension (encoded as an attribute).
10423  if (Expr *E = (Expr*) D.getAsmLabel()) {
10424  // The parser guarantees this is a string.
10425  StringLiteral *SE = cast<StringLiteral>(E);
10426  NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10427  /*IsLiteralLabel=*/true,
10428  SE->getStrTokenLoc(0)));
10429  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10430  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10431  ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10432  if (I != ExtnameUndeclaredIdentifiers.end()) {
10433  if (isDeclExternC(NewFD)) {
10434  NewFD->addAttr(I->second);
10435  ExtnameUndeclaredIdentifiers.erase(I);
10436  } else
10437  Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10438  << /*Variable*/0 << NewFD;
10439  }
10440  }
10441 
10442  // Copy the parameter declarations from the declarator D to the function
10443  // declaration NewFD, if they are available. First scavenge them into Params.
10445  unsigned FTIIdx;
10446  if (D.isFunctionDeclarator(FTIIdx)) {
10448 
10449  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10450  // function that takes no arguments, not a function that takes a
10451  // single void argument.
10452  // We let through "const void" here because Sema::GetTypeForDeclarator
10453  // already checks for that case.
10454  if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10455  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10456  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10457  assert(Param->getDeclContext() != NewFD && "Was set before ?");
10458  Param->setDeclContext(NewFD);
10459  Params.push_back(Param);
10460 
10461  if (Param->isInvalidDecl())
10462  NewFD->setInvalidDecl();
10463  }
10464  }
10465 
10466  if (!getLangOpts().CPlusPlus) {
10467  // In C, find all the tag declarations from the prototype and move them
10468  // into the function DeclContext. Remove them from the surrounding tag
10469  // injection context of the function, which is typically but not always
10470  // the TU.
10471  DeclContext *PrototypeTagContext =
10473  for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10474  auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10475 
10476  // We don't want to reparent enumerators. Look at their parent enum
10477  // instead.
10478  if (!TD) {
10479  if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10480  TD = cast<EnumDecl>(ECD->getDeclContext());
10481  }
10482  if (!TD)
10483  continue;
10484  DeclContext *TagDC = TD->getLexicalDeclContext();
10485  if (!TagDC->containsDecl(TD))
10486  continue;
10487  TagDC->removeDecl(TD);
10488  TD->setDeclContext(NewFD);
10489  NewFD->addDecl(TD);
10490 
10491  // Preserve the lexical DeclContext if it is not the surrounding tag
10492  // injection context of the FD. In this example, the semantic context of
10493  // E will be f and the lexical context will be S, while both the
10494  // semantic and lexical contexts of S will be f:
10495  // void f(struct S { enum E { a } f; } s);
10496  if (TagDC != PrototypeTagContext)
10497  TD->setLexicalDeclContext(TagDC);
10498  }
10499  }
10500  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10501  // When we're declaring a function with a typedef, typeof, etc as in the
10502  // following example, we'll need to synthesize (unnamed)
10503  // parameters for use in the declaration.
10504  //
10505  // @code
10506  // typedef void fn(int);
10507  // fn f;
10508  // @endcode
10509 
10510  // Synthesize a parameter for each argument type.
10511  for (const auto &AI : FT->param_types()) {
10512  ParmVarDecl *Param =
10513  BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10514  Param->setScopeInfo(0, Params.size());
10515  Params.push_back(Param);
10516  }
10517  } else {
10518  assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10519  "Should not need args for typedef of non-prototype fn");
10520  }
10521 
10522  // Finally, we know we have the right number of parameters, install them.
10523  NewFD->setParams(Params);
10524 
10525  if (D.getDeclSpec().isNoreturnSpecified())
10526  NewFD->addAttr(
10527  C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10528 
10529  // Functions returning a variably modified type violate C99 6.7.5.2p2
10530  // because all functions have linkage.
10531  if (!NewFD->isInvalidDecl() &&
10532  NewFD->getReturnType()->isVariablyModifiedType()) {
10533  Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10534  NewFD->setInvalidDecl();
10535  }
10536 
10537  // Apply an implicit SectionAttr if '#pragma clang section text' is active
10538  if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10539  !NewFD->hasAttr<SectionAttr>())
10540  NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10541  Context, PragmaClangTextSection.SectionName,
10542  PragmaClangTextSection.PragmaLocation));
10543 
10544  // Apply an implicit SectionAttr if #pragma code_seg is active.
10545  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10546  !NewFD->hasAttr<SectionAttr>()) {
10547  NewFD->addAttr(SectionAttr::CreateImplicit(
10548  Context, CodeSegStack.CurrentValue->getString(),
10549  CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10550  if (UnifySection(CodeSegStack.CurrentValue->getString(),
10553  NewFD))
10554  NewFD->dropAttr<SectionAttr>();
10555  }
10556 
10557  // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10558  // active.
10559  if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10560  !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10561  NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10562  Context, PragmaClangTextSection.PragmaLocation));
10563 
10564  // Apply an implicit CodeSegAttr from class declspec or
10565  // apply an implicit SectionAttr from #pragma code_seg if active.
10566  if (!NewFD->hasAttr<CodeSegAttr>()) {
10567  if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10568  D.isFunctionDefinition())) {
10569  NewFD->addAttr(SAttr);
10570  }
10571  }
10572 
10573  // Handle attributes.
10574  ProcessDeclAttributes(S, NewFD, D);
10575  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10576  if (NewTVA && !NewTVA->isDefaultVersion() &&
10577  !Context.getTargetInfo().hasFeature("fmv")) {
10578  // Don't add to scope fmv functions declarations if fmv disabled
10579  AddToScope = false;
10580  return NewFD;
10581  }
10582 
10583  if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10584  // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10585  // type.
10586  //
10587  // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10588  // type declaration will generate a compilation error.
10589  LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10590  if (AddressSpace != LangAS::Default) {
10591  Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10592  NewFD->setInvalidDecl();
10593  }
10594  }
10595 
10596  if (!getLangOpts().CPlusPlus) {
10597  // Perform semantic checking on the function declaration.
10598  if (!NewFD->isInvalidDecl() && NewFD->isMain())
10599  CheckMain(NewFD, D.getDeclSpec());
10600 
10601  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10602  CheckMSVCRTEntryPoint(NewFD);
10603 
10604  if (!NewFD->isInvalidDecl())
10605  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10606  isMemberSpecialization,
10607  D.isFunctionDefinition()));
10608  else if (!Previous.empty())
10609  // Recover gracefully from an invalid redeclaration.
10610  D.setRedeclaration(true);
10611  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10612  Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10613  "previous declaration set still overloaded");
10614 
10615  // Diagnose no-prototype function declarations with calling conventions that
10616  // don't support variadic calls. Only do this in C and do it after merging
10617  // possibly prototyped redeclarations.
10618  const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10619  if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10620  CallingConv CC = FT->getExtInfo().getCC();
10621  if (!supportsVariadicCall(CC)) {
10622  // Windows system headers sometimes accidentally use stdcall without
10623  // (void) parameters, so we relax this to a warning.
10624  int DiagID =
10625  CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10626  Diag(NewFD->getLocation(), DiagID)
10628  }
10629  }
10630 
10633  checkNonTrivialCUnion(NewFD->getReturnType(),
10635  NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10636  } else {
10637  // C++11 [replacement.functions]p3:
10638  // The program's definitions shall not be specified as inline.
10639  //
10640  // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10641  //
10642  // Suppress the diagnostic if the function is __attribute__((used)), since
10643  // that forces an external definition to be emitted.
10644  if (D.getDeclSpec().isInlineSpecified() &&
10646  !NewFD->hasAttr<UsedAttr>())
10648  diag::ext_operator_new_delete_declared_inline)
10649  << NewFD->getDeclName();
10650 
10651  if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10652  // C++20 [dcl.decl.general]p4:
10653  // The optional requires-clause in an init-declarator or
10654  // member-declarator shall be present only if the declarator declares a
10655  // templated function.
10656  //
10657  // C++20 [temp.pre]p8:
10658  // An entity is templated if it is
10659  // - a template,
10660  // - an entity defined or created in a templated entity,
10661  // - a member of a templated entity,
10662  // - an enumerator for an enumeration that is a templated entity, or
10663  // - the closure type of a lambda-expression appearing in the
10664  // declaration of a templated entity.
10665  //
10666  // [Note 6: A local class, a local or block variable, or a friend
10667  // function defined in a templated entity is a templated entity.
10668  // — end note]
10669  //
10670  // A templated function is a function template or a function that is
10671  // templated. A templated class is a class template or a class that is
10672  // templated. A templated variable is a variable template or a variable
10673  // that is templated.
10674  if (!FunctionTemplate) {
10675  if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10676  // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10677  // An explicit specialization shall not have a trailing
10678  // requires-clause unless it declares a function template.
10679  //
10680  // Since a friend function template specialization cannot be
10681  // definition, and since a non-template friend declaration with a
10682  // trailing requires-clause must be a definition, we diagnose
10683  // friend function template specializations with trailing
10684  // requires-clauses on the same path as explicit specializations
10685  // even though they aren't necessarily prohibited by the same
10686  // language rule.
10687  Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10688  << isFriend;
10689  } else if (isFriend && NewFD->isTemplated() &&
10690  !D.isFunctionDefinition()) {
10691  // C++ [temp.friend]p9:
10692  // A non-template friend declaration with a requires-clause shall be
10693  // a definition.
10694  Diag(NewFD->getBeginLoc(),
10695  diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10696  NewFD->setInvalidDecl();
10697  } else if (!NewFD->isTemplated() ||
10698  !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10699  Diag(TRC->getBeginLoc(),
10700  diag::err_constrained_non_templated_function);
10701  }
10702  }
10703  }
10704 
10705  // We do not add HD attributes to specializations here because
10706  // they may have different constexpr-ness compared to their
10707  // templates and, after maybeAddHostDeviceAttrs() is applied,
10708  // may end up with different effective targets. Instead, a
10709  // specialization inherits its target attributes from its template
10710  // in the CheckFunctionTemplateSpecialization() call below.
10711  if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10712  CUDA().maybeAddHostDeviceAttrs(NewFD, Previous);
10713 
10714  // Handle explict specializations of function templates
10715  // and friend function declarations with an explicit
10716  // template argument list.
10717  if (isFunctionTemplateSpecialization) {
10718  bool isDependentSpecialization = false;
10719  if (isFriend) {
10720  // For friend function specializations, this is a dependent
10721  // specialization if its semantic context is dependent, its
10722  // type is dependent, or if its template-id is dependent.
10723  isDependentSpecialization =
10724  DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10725  (HasExplicitTemplateArgs &&
10728  TemplateArgs.arguments()));
10729  assert((!isDependentSpecialization ||
10730  (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10731  "dependent friend function specialization without template "
10732  "args");
10733  } else {
10734  // For class-scope explicit specializations of function templates,
10735  // if the lexical context is dependent, then the specialization
10736  // is dependent.
10737  isDependentSpecialization =
10738  CurContext->isRecord() && CurContext->isDependentContext();
10739  }
10740 
10741  TemplateArgumentListInfo *ExplicitTemplateArgs =
10742  HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10743  if (isDependentSpecialization) {
10744  // If it's a dependent specialization, it may not be possible
10745  // to determine the primary template (for explicit specializations)
10746  // or befriended declaration (for friends) until the enclosing
10747  // template is instantiated. In such cases, we store the declarations
10748  // found by name lookup and defer resolution until instantiation.
10749  if (CheckDependentFunctionTemplateSpecialization(
10750  NewFD, ExplicitTemplateArgs, Previous))
10751  NewFD->setInvalidDecl();
10752  } else if (!NewFD->isInvalidDecl()) {
10753  if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10754  Previous))
10755  NewFD->setInvalidDecl();
10756  }
10757 
10758  // C++ [dcl.stc]p1:
10759  // A storage-class-specifier shall not be specified in an explicit
10760  // specialization (14.7.3)
10761  // FIXME: We should be checking this for dependent specializations.
10764  if (Info && SC != SC_None) {
10765  if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10766  Diag(NewFD->getLocation(),
10767  diag::err_explicit_specialization_inconsistent_storage_class)
10768  << SC
10771 
10772  else
10773  Diag(NewFD->getLocation(),
10774  diag::ext_explicit_specialization_storage_class)
10777  }
10778  } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10779  if (CheckMemberSpecialization(NewFD, Previous))
10780  NewFD->setInvalidDecl();
10781  }
10782 
10783  // Perform semantic checking on the function declaration.
10784  if (!NewFD->isInvalidDecl() && NewFD->isMain())
10785  CheckMain(NewFD, D.getDeclSpec());
10786 
10787  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10788  CheckMSVCRTEntryPoint(NewFD);
10789 
10790  if (!NewFD->isInvalidDecl())
10791  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10792  isMemberSpecialization,
10793  D.isFunctionDefinition()));
10794  else if (!Previous.empty())
10795  // Recover gracefully from an invalid redeclaration.
10796  D.setRedeclaration(true);
10797 
10798  assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10799  !D.isRedeclaration() ||
10800  Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10801  "previous declaration set still overloaded");
10802 
10803  NamedDecl *PrincipalDecl = (FunctionTemplate
10804  ? cast<NamedDecl>(FunctionTemplate)
10805  : NewFD);
10806 
10807  if (isFriend && NewFD->getPreviousDecl()) {
10808  AccessSpecifier Access = AS_public;
10809  if (!NewFD->isInvalidDecl())
10810  Access = NewFD->getPreviousDecl()->getAccess();
10811 
10812  NewFD->setAccess(Access);
10813  if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10814  }
10815 
10816  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10818  PrincipalDecl->setNonMemberOperator();
10819 
10820  // If we have a function template, check the template parameter
10821  // list. This will check and merge default template arguments.
10822  if (FunctionTemplate) {
10823  FunctionTemplateDecl *PrevTemplate =
10824  FunctionTemplate->getPreviousDecl();
10825  CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10826  PrevTemplate ? PrevTemplate->getTemplateParameters()
10827  : nullptr,
10829  ? (D.isFunctionDefinition()
10830  ? TPC_FriendFunctionTemplateDefinition
10831  : TPC_FriendFunctionTemplate)
10832  : (D.getCXXScopeSpec().isSet() &&
10833  DC && DC->isRecord() &&
10834  DC->isDependentContext())
10835  ? TPC_ClassTemplateMember
10836  : TPC_FunctionTemplate);
10837  }
10838 
10839  if (NewFD->isInvalidDecl()) {
10840  // Ignore all the rest of this.
10841  } else if (!D.isRedeclaration()) {
10842  struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10843  AddToScope };
10844  // Fake up an access specifier if it's supposed to be a class member.
10845  if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10846  NewFD->setAccess(AS_public);
10847 
10848  // Qualified decls generally require a previous declaration.
10849  if (D.getCXXScopeSpec().isSet()) {
10850  // ...with the major exception of templated-scope or
10851  // dependent-scope friend declarations.
10852 
10853  // TODO: we currently also suppress this check in dependent
10854  // contexts because (1) the parameter depth will be off when
10855  // matching friend templates and (2) we might actually be
10856  // selecting a friend based on a dependent factor. But there
10857  // are situations where these conditions don't apply and we
10858  // can actually do this check immediately.
10859  //
10860  // Unless the scope is dependent, it's always an error if qualified
10861  // redeclaration lookup found nothing at all. Diagnose that now;
10862  // nothing will diagnose that error later.
10863  if (isFriend &&
10865  (!Previous.empty() && CurContext->isDependentContext()))) {
10866  // ignore these
10867  } else if (NewFD->isCPUDispatchMultiVersion() ||
10868  NewFD->isCPUSpecificMultiVersion()) {
10869  // ignore this, we allow the redeclaration behavior here to create new
10870  // versions of the function.
10871  } else {
10872  // The user tried to provide an out-of-line definition for a
10873  // function that is a member of a class or namespace, but there
10874  // was no such member function declared (C++ [class.mfct]p2,
10875  // C++ [namespace.memdef]p2). For example:
10876  //
10877  // class X {
10878  // void f() const;
10879  // };
10880  //
10881  // void X::f() { } // ill-formed
10882  //
10883  // Complain about this problem, and attempt to suggest close
10884  // matches (e.g., those that differ only in cv-qualifiers and
10885  // whether the parameter types are references).
10886 
10888  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10889  AddToScope = ExtraArgs.AddToScope;
10890  return Result;
10891  }
10892  }
10893 
10894  // Unqualified local friend declarations are required to resolve
10895  // to something.
10896  } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10898  *this, Previous, NewFD, ExtraArgs, true, S)) {
10899  AddToScope = ExtraArgs.AddToScope;
10900  return Result;
10901  }
10902  }
10903  } else if (!D.isFunctionDefinition() &&
10904  isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10905  !isFriend && !isFunctionTemplateSpecialization &&
10906  !isMemberSpecialization) {
10907  // An out-of-line member function declaration must also be a
10908  // definition (C++ [class.mfct]p2).
10909  // Note that this is not the case for explicit specializations of
10910  // function templates or member functions of class templates, per
10911  // C++ [temp.expl.spec]p2. We also allow these declarations as an
10912  // extension for compatibility with old SWIG code which likes to
10913  // generate them.
10914  Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10915  << D.getCXXScopeSpec().getRange();
10916  }
10917  }
10918 
10919  if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10920  // Any top level function could potentially be specified as an entry.
10921  if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10922  HLSL().ActOnTopLevelFunction(NewFD);
10923 
10924  if (NewFD->hasAttr<HLSLShaderAttr>())
10925  HLSL().CheckEntryPoint(NewFD);
10926  }
10927 
10928  // If this is the first declaration of a library builtin function, add
10929  // attributes as appropriate.
10930  if (!D.isRedeclaration()) {
10931  if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10932  if (unsigned BuiltinID = II->getBuiltinID()) {
10933  bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10934  if (!InStdNamespace &&
10936  if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10937  // Validate the type matches unless this builtin is specified as
10938  // matching regardless of its declared type.
10939  if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10940  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10941  } else {
10943  LookupNecessaryTypesForBuiltin(S, BuiltinID);
10944  QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10945 
10946  if (!Error && !BuiltinType.isNull() &&
10948  NewFD->getType(), BuiltinType))
10949  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10950  }
10951  }
10952  } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10953  isStdBuiltin(Context, NewFD, BuiltinID)) {
10954  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10955  }
10956  }
10957  }
10958  }
10959 
10960  ProcessPragmaWeak(S, NewFD);
10961  checkAttributesAfterMerging(*this, *NewFD);
10962 
10963  AddKnownFunctionAttributes(NewFD);
10964 
10965  if (NewFD->hasAttr<OverloadableAttr>() &&
10966  !NewFD->getType()->getAs<FunctionProtoType>()) {
10967  Diag(NewFD->getLocation(),
10968  diag::err_attribute_overloadable_no_prototype)
10969  << NewFD;
10970  NewFD->dropAttr<OverloadableAttr>();
10971  }
10972 
10973  // If there's a #pragma GCC visibility in scope, and this isn't a class
10974  // member, set the visibility of this function.
10975  if (!DC->isRecord() && NewFD->isExternallyVisible())
10976  AddPushedVisibilityAttribute(NewFD);
10977 
10978  // If there's a #pragma clang arc_cf_code_audited in scope, consider
10979  // marking the function.
10980  AddCFAuditedAttribute(NewFD);
10981 
10982  // If this is a function definition, check if we have to apply any
10983  // attributes (i.e. optnone and no_builtin) due to a pragma.
10984  if (D.isFunctionDefinition()) {
10985  AddRangeBasedOptnone(NewFD);
10986  AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10987  AddSectionMSAllocText(NewFD);
10988  ModifyFnAttributesMSPragmaOptimize(NewFD);
10989  }
10990 
10991  // If this is the first declaration of an extern C variable, update
10992  // the map of such variables.
10993  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10994  isIncompleteDeclExternC(*this, NewFD))
10995  RegisterLocallyScopedExternCDecl(NewFD, S);
10996 
10997  // Set this FunctionDecl's range up to the right paren.
10998  NewFD->setRangeEnd(D.getSourceRange().getEnd());
10999 
11000  if (D.isRedeclaration() && !Previous.empty()) {
11001  NamedDecl *Prev = Previous.getRepresentativeDecl();
11002  checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11003  isMemberSpecialization ||
11004  isFunctionTemplateSpecialization,
11005  D.isFunctionDefinition());
11006  }
11007 
11008  if (getLangOpts().CUDA) {
11009  IdentifierInfo *II = NewFD->getIdentifier();
11010  if (II && II->isStr(CUDA().getConfigureFuncName()) &&
11011  !NewFD->isInvalidDecl() &&
11013  if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11014  Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11015  << CUDA().getConfigureFuncName();
11016  Context.setcudaConfigureCallDecl(NewFD);
11017  }
11018 
11019  // Variadic functions, other than a *declaration* of printf, are not allowed
11020  // in device-side CUDA code, unless someone passed
11021  // -fcuda-allow-variadic-functions.
11022  if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
11023  (NewFD->hasAttr<CUDADeviceAttr>() ||
11024  NewFD->hasAttr<CUDAGlobalAttr>()) &&
11025  !(II && II->isStr("printf") && NewFD->isExternC() &&
11026  !D.isFunctionDefinition())) {
11027  Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
11028  }
11029  }
11030 
11031  MarkUnusedFileScopedDecl(NewFD);
11032 
11033 
11034 
11035  if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
11036  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11037  if (SC == SC_Static) {
11038  Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11039  D.setInvalidType();
11040  }
11041 
11042  // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11043  if (!NewFD->getReturnType()->isVoidType()) {
11044  SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11045  Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11046  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11047  : FixItHint());
11048  D.setInvalidType();
11049  }
11050 
11052  for (auto *Param : NewFD->parameters())
11053  checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11054 
11055  if (getLangOpts().OpenCLCPlusPlus) {
11056  if (DC->isRecord()) {
11057  Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11058  D.setInvalidType();
11059  }
11060  if (FunctionTemplate) {
11061  Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11062  D.setInvalidType();
11063  }
11064  }
11065  }
11066 
11067  if (getLangOpts().CPlusPlus) {
11068  // Precalculate whether this is a friend function template with a constraint
11069  // that depends on an enclosing template, per [temp.friend]p9.
11070  if (isFriend && FunctionTemplate &&
11071  FriendConstraintsDependOnEnclosingTemplate(NewFD)) {
11073 
11074  // C++ [temp.friend]p9:
11075  // A friend function template with a constraint that depends on a
11076  // template parameter from an enclosing template shall be a definition.
11077  if (!D.isFunctionDefinition()) {
11078  Diag(NewFD->getBeginLoc(),
11079  diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11080  NewFD->setInvalidDecl();
11081  }
11082  }
11083 
11084  if (FunctionTemplate) {
11085  if (NewFD->isInvalidDecl())
11086  FunctionTemplate->setInvalidDecl();
11087  return FunctionTemplate;
11088  }
11089 
11090  if (isMemberSpecialization && !NewFD->isInvalidDecl())
11091  CompleteMemberSpecialization(NewFD, Previous);
11092  }
11093 
11094  for (const ParmVarDecl *Param : NewFD->parameters()) {
11095  QualType PT = Param->getType();
11096 
11097  if (const PipeType *PipeTy = PT->getAs<PipeType>()) {
11098  QualType ElemTy = PipeTy->getElementType();
11099  if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
11100  Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
11101  D.setInvalidType();
11102  }
11103  }
11104  // WebAssembly tables can't be used as function parameters.
11105  if (Context.getTargetInfo().getTriple().isWasm()) {
11107  Diag(Param->getTypeSpecStartLoc(),
11108  diag::err_wasm_table_as_function_parameter);
11109  D.setInvalidType();
11110  }
11111  }
11112  }
11113 
11114  // Diagnose availability attributes. Availability cannot be used on functions
11115  // that are run during load/unload.
11116  if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11117  if (NewFD->hasAttr<ConstructorAttr>()) {
11118  Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11119  << 1;
11120  NewFD->dropAttr<AvailabilityAttr>();
11121  }
11122  if (NewFD->hasAttr<DestructorAttr>()) {
11123  Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11124  << 2;
11125  NewFD->dropAttr<AvailabilityAttr>();
11126  }
11127  }
11128 
11129  // Diagnose no_builtin attribute on function declaration that are not a
11130  // definition.
11131  // FIXME: We should really be doing this in
11132  // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11133  // the FunctionDecl and at this point of the code
11134  // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11135  // because Sema::ActOnStartOfFunctionDef has not been called yet.
11136  if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11137  switch (D.getFunctionDefinitionKind()) {
11140  Diag(NBA->getLocation(),
11141  diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11142  << NBA->getSpelling();
11143  break;
11145  Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11146  << NBA->getSpelling();
11147  break;
11149  break;
11150  }
11151 
11152  return NewFD;
11153 }
11154 
11155 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
11156 /// when __declspec(code_seg) "is applied to a class, all member functions of
11157 /// the class and nested classes -- this includes compiler-generated special
11158 /// member functions -- are put in the specified segment."
11159 /// The actual behavior is a little more complicated. The Microsoft compiler
11160 /// won't check outer classes if there is an active value from #pragma code_seg.
11161 /// The CodeSeg is always applied from the direct parent but only from outer
11162 /// classes when the #pragma code_seg stack is empty. See:
11163 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11164 /// available since MS has removed the page.
11166  const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11167  if (!Method)
11168  return nullptr;
11169  const CXXRecordDecl *Parent = Method->getParent();
11170  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11171  Attr *NewAttr = SAttr->clone(S.getASTContext());
11172  NewAttr->setImplicit(true);
11173  return NewAttr;
11174  }
11175 
11176  // The Microsoft compiler won't check outer classes for the CodeSeg
11177  // when the #pragma code_seg stack is active.
11178  if (S.CodeSegStack.CurrentValue)
11179  return nullptr;
11180 
11181  while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11182  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11183  Attr *NewAttr = SAttr->clone(S.getASTContext());
11184  NewAttr->setImplicit(true);
11185  return NewAttr;
11186  }
11187  }
11188  return nullptr;
11189 }
11190 
11191 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
11192 /// containing class. Otherwise it will return implicit SectionAttr if the
11193 /// function is a definition and there is an active value on CodeSegStack
11194 /// (from the current #pragma code-seg value).
11195 ///
11196 /// \param FD Function being declared.
11197 /// \param IsDefinition Whether it is a definition or just a declaration.
11198 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
11199 /// nullptr if no attribute should be added.
11201  bool IsDefinition) {
11202  if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11203  return A;
11204  if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11205  CodeSegStack.CurrentValue)
11206  return SectionAttr::CreateImplicit(
11207  getASTContext(), CodeSegStack.CurrentValue->getString(),
11208  CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11209  return nullptr;
11210 }
11211 
11212 /// Determines if we can perform a correct type check for \p D as a
11213 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
11214 /// best-effort check.
11215 ///
11216 /// \param NewD The new declaration.
11217 /// \param OldD The old declaration.
11218 /// \param NewT The portion of the type of the new declaration to check.
11219 /// \param OldT The portion of the type of the old declaration to check.
11221  QualType NewT, QualType OldT) {
11222  if (!NewD->getLexicalDeclContext()->isDependentContext())
11223  return true;
11224 
11225  // For dependently-typed local extern declarations and friends, we can't
11226  // perform a correct type check in general until instantiation:
11227  //
11228  // int f();
11229  // template<typename T> void g() { T f(); }
11230  //
11231  // (valid if g() is only instantiated with T = int).
11232  if (NewT->isDependentType() &&
11233  (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11234  return false;
11235 
11236  // Similarly, if the previous declaration was a dependent local extern
11237  // declaration, we don't really know its type yet.
11238  if (OldT->isDependentType() && OldD->isLocalExternDecl())
11239  return false;
11240 
11241  return true;
11242 }
11243 
11244 /// Checks if the new declaration declared in dependent context must be
11245 /// put in the same redeclaration chain as the specified declaration.
11246 ///
11247 /// \param D Declaration that is checked.
11248 /// \param PrevDecl Previous declaration found with proper lookup method for the
11249 /// same declaration name.
11250 /// \returns True if D must be added to the redeclaration chain which PrevDecl
11251 /// belongs to.
11252 ///
11255  return true;
11256 
11257  // Don't chain dependent friend function definitions until instantiation, to
11258  // permit cases like
11259  //
11260  // void func();
11261  // template<typename T> class C1 { friend void func() {} };
11262  // template<typename T> class C2 { friend void func() {} };
11263  //
11264  // ... which is valid if only one of C1 and C2 is ever instantiated.
11265  //
11266  // FIXME: This need only apply to function definitions. For now, we proxy
11267  // this by checking for a file-scope function. We do not want this to apply
11268  // to friend declarations nominating member functions, because that gets in
11269  // the way of access checks.
11270  if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11271  return false;
11272 
11273  auto *VD = dyn_cast<ValueDecl>(D);
11274  auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11275  return !VD || !PrevVD ||
11276  canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11277  PrevVD->getType());
11278 }
11279 
11280 /// Check the target or target_version attribute of the function for
11281 /// MultiVersion validity.
11282 ///
11283 /// Returns true if there was an error, false otherwise.
11284 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11285  const auto *TA = FD->getAttr<TargetAttr>();
11286  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11287  assert(
11288  (TA || TVA) &&
11289  "MultiVersion candidate requires a target or target_version attribute");
11291  enum ErrType { Feature = 0, Architecture = 1 };
11292 
11293  if (TA) {
11294  ParsedTargetAttr ParseInfo =
11295  S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11296  if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11297  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11298  << Architecture << ParseInfo.CPU;
11299  return true;
11300  }
11301  for (const auto &Feat : ParseInfo.Features) {
11302  auto BareFeat = StringRef{Feat}.substr(1);
11303  if (Feat[0] == '-') {
11304  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11305  << Feature << ("no-" + BareFeat).str();
11306  return true;
11307  }
11308 
11309  if (!TargetInfo.validateCpuSupports(BareFeat) ||
11310  !TargetInfo.isValidFeatureName(BareFeat)) {
11311  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11312  << Feature << BareFeat;
11313  return true;
11314  }
11315  }
11316  }
11317 
11318  if (TVA) {
11320  TVA->getFeatures(Feats);
11321  for (const auto &Feat : Feats) {
11322  if (!TargetInfo.validateCpuSupports(Feat)) {
11323  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11324  << Feature << Feat;
11325  return true;
11326  }
11327  }
11328  }
11329  return false;
11330 }
11331 
11332 // Provide a white-list of attributes that are allowed to be combined with
11333 // multiversion functions.
11335  MultiVersionKind MVKind) {
11336  // Note: this list/diagnosis must match the list in
11337  // checkMultiversionAttributesAllSame.
11338  switch (Kind) {
11339  default:
11340  return false;
11341  case attr::Used:
11342  return MVKind == MultiVersionKind::Target;
11343  case attr::NonNull:
11344  case attr::NoThrow:
11345  return true;
11346  }
11347 }
11348 
11350  const FunctionDecl *FD,
11351  const FunctionDecl *CausedFD,
11352  MultiVersionKind MVKind) {
11353  const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11354  S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11355  << static_cast<unsigned>(MVKind) << A;
11356  if (CausedFD)
11357  S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11358  return true;
11359  };
11360 
11361  for (const Attr *A : FD->attrs()) {
11362  switch (A->getKind()) {
11363  case attr::CPUDispatch:
11364  case attr::CPUSpecific:
11365  if (MVKind != MultiVersionKind::CPUDispatch &&
11367  return Diagnose(S, A);
11368  break;
11369  case attr::Target:
11370  if (MVKind != MultiVersionKind::Target)
11371  return Diagnose(S, A);
11372  break;
11373  case attr::TargetVersion:
11374  if (MVKind != MultiVersionKind::TargetVersion &&
11376  return Diagnose(S, A);
11377  break;
11378  case attr::TargetClones:
11379  if (MVKind != MultiVersionKind::TargetClones &&
11381  return Diagnose(S, A);
11382  break;
11383  default:
11384  if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11385  return Diagnose(S, A);
11386  break;
11387  }
11388  }
11389  return false;
11390 }
11391 
11393  const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11394  const PartialDiagnostic &NoProtoDiagID,
11395  const PartialDiagnosticAt &NoteCausedDiagIDAt,
11396  const PartialDiagnosticAt &NoSupportDiagIDAt,
11397  const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11398  bool ConstexprSupported, bool CLinkageMayDiffer) {
11399  enum DoesntSupport {
11400  FuncTemplates = 0,
11401  VirtFuncs = 1,
11402  DeducedReturn = 2,
11403  Constructors = 3,
11404  Destructors = 4,
11405  DeletedFuncs = 5,
11406  DefaultedFuncs = 6,
11407  ConstexprFuncs = 7,
11408  ConstevalFuncs = 8,
11409  Lambda = 9,
11410  };
11411  enum Different {
11412  CallingConv = 0,
11413  ReturnType = 1,
11414  ConstexprSpec = 2,
11415  InlineSpec = 3,
11416  Linkage = 4,
11417  LanguageLinkage = 5,
11418  };
11419 
11420  if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11421  !OldFD->getType()->getAs<FunctionProtoType>()) {
11422  Diag(OldFD->getLocation(), NoProtoDiagID);
11423  Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11424  return true;
11425  }
11426 
11427  if (NoProtoDiagID.getDiagID() != 0 &&
11428  !NewFD->getType()->getAs<FunctionProtoType>())
11429  return Diag(NewFD->getLocation(), NoProtoDiagID);
11430 
11431  if (!TemplatesSupported &&
11433  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11434  << FuncTemplates;
11435 
11436  if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11437  if (NewCXXFD->isVirtual())
11438  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11439  << VirtFuncs;
11440 
11441  if (isa<CXXConstructorDecl>(NewCXXFD))
11442  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11443  << Constructors;
11444 
11445  if (isa<CXXDestructorDecl>(NewCXXFD))
11446  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11447  << Destructors;
11448  }
11449 
11450  if (NewFD->isDeleted())
11451  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11452  << DeletedFuncs;
11453 
11454  if (NewFD->isDefaulted())
11455  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11456  << DefaultedFuncs;
11457 
11458  if (!ConstexprSupported && NewFD->isConstexpr())
11459  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11460  << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11461 
11462  QualType NewQType = Context.getCanonicalType(NewFD->getType());
11463  const auto *NewType = cast<FunctionType>(NewQType);
11464  QualType NewReturnType = NewType->getReturnType();
11465 
11466  if (NewReturnType->isUndeducedType())
11467  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11468  << DeducedReturn;
11469 
11470  // Ensure the return type is identical.
11471  if (OldFD) {
11472  QualType OldQType = Context.getCanonicalType(OldFD->getType());
11473  const auto *OldType = cast<FunctionType>(OldQType);
11474  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11475  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11476 
11477  if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11478  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11479 
11480  QualType OldReturnType = OldType->getReturnType();
11481 
11482  if (OldReturnType != NewReturnType)
11483  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11484 
11485  if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11486  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11487 
11488  if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11489  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11490 
11491  if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11492  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11493 
11494  if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11495  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11496 
11497  if (CheckEquivalentExceptionSpec(
11498  OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11499  NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11500  return true;
11501  }
11502  return false;
11503 }
11504 
11506  const FunctionDecl *NewFD,
11507  bool CausesMV,
11508  MultiVersionKind MVKind) {
11510  S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11511  if (OldFD)
11512  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11513  return true;
11514  }
11515 
11516  bool IsCPUSpecificCPUDispatchMVKind =
11517  MVKind == MultiVersionKind::CPUDispatch ||
11519 
11520  if (CausesMV && OldFD &&
11521  checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11522  return true;
11523 
11524  if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11525  return true;
11526 
11527  // Only allow transition to MultiVersion if it hasn't been used.
11528  if (OldFD && CausesMV && OldFD->isUsed(false))
11529  return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11530 
11532  OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11534  S.PDiag(diag::note_multiversioning_caused_here)),
11536  S.PDiag(diag::err_multiversion_doesnt_support)
11537  << static_cast<unsigned>(MVKind)),
11539  S.PDiag(diag::err_multiversion_diff)),
11540  /*TemplatesSupported=*/false,
11541  /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11542  /*CLinkageMayDiffer=*/false);
11543 }
11544 
11545 /// Check the validity of a multiversion function declaration that is the
11546 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11547 ///
11548 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11549 ///
11550 /// Returns true if there was an error, false otherwise.
11552  MultiVersionKind MVKind = FD->getMultiVersionKind();
11553  assert(MVKind != MultiVersionKind::None &&
11554  "Function lacks multiversion attribute");
11555  const auto *TA = FD->getAttr<TargetAttr>();
11556  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11557  // The target attribute only causes MV if this declaration is the default,
11558  // otherwise it is treated as a normal function.
11559  if (TA && !TA->isDefaultVersion())
11560  return false;
11561 
11562  if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11563  FD->setInvalidDecl();
11564  return true;
11565  }
11566 
11567  if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11568  FD->setInvalidDecl();
11569  return true;
11570  }
11571 
11572  FD->setIsMultiVersion();
11573  return false;
11574 }
11575 
11577  for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11579  return true;
11580  }
11581 
11582  return false;
11583 }
11584 
11586  if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11587  return;
11588 
11589  MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11590  MultiVersionKind MVKindTo = To->getMultiVersionKind();
11591 
11592  if (MVKindTo == MultiVersionKind::None &&
11593  (MVKindFrom == MultiVersionKind::TargetVersion ||
11594  MVKindFrom == MultiVersionKind::TargetClones)) {
11595  To->setIsMultiVersion();
11596  To->addAttr(TargetVersionAttr::CreateImplicit(
11597  To->getASTContext(), "default", To->getSourceRange()));
11598  }
11599 }
11600 
11602  FunctionDecl *NewFD,
11603  bool &Redeclaration,
11604  NamedDecl *&OldDecl,
11606  assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11607 
11608  // The definitions should be allowed in any order. If we have discovered
11609  // a new target version and the preceeding was the default, then add the
11610  // corresponding attribute to it.
11611  patchDefaultTargetVersion(NewFD, OldFD);
11612 
11613  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11614  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11615  const auto *OldTA = OldFD->getAttr<TargetAttr>();
11616  const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11617  // If the old decl is NOT MultiVersioned yet, and we don't cause that
11618  // to change, this is a simple redeclaration.
11619  if ((NewTA && !NewTA->isDefaultVersion() &&
11620  (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11621  (NewTVA && !NewTVA->isDefaultVersion() &&
11622  (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11623  return false;
11624 
11625  // Otherwise, this decl causes MultiVersioning.
11626  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11629  NewFD->setInvalidDecl();
11630  return true;
11631  }
11632 
11633  if (CheckMultiVersionValue(S, NewFD)) {
11634  NewFD->setInvalidDecl();
11635  return true;
11636  }
11637 
11638  // If this is 'default', permit the forward declaration.
11639  if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11640  (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11641  Redeclaration = true;
11642  OldDecl = OldFD;
11643  OldFD->setIsMultiVersion();
11644  NewFD->setIsMultiVersion();
11645  return false;
11646  }
11647 
11648  if (CheckMultiVersionValue(S, OldFD)) {
11649  S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11650  NewFD->setInvalidDecl();
11651  return true;
11652  }
11653 
11654  if (NewTA) {
11655  ParsedTargetAttr OldParsed =
11657  OldTA->getFeaturesStr());
11658  llvm::sort(OldParsed.Features);
11659  ParsedTargetAttr NewParsed =
11661  NewTA->getFeaturesStr());
11662  // Sort order doesn't matter, it just needs to be consistent.
11663  llvm::sort(NewParsed.Features);
11664  if (OldParsed == NewParsed) {
11665  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11666  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11667  NewFD->setInvalidDecl();
11668  return true;
11669  }
11670  }
11671 
11672  if (NewTVA) {
11674  OldTVA->getFeatures(Feats);
11675  llvm::sort(Feats);
11677  NewTVA->getFeatures(NewFeats);
11678  llvm::sort(NewFeats);
11679 
11680  if (Feats == NewFeats) {
11681  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11682  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11683  NewFD->setInvalidDecl();
11684  return true;
11685  }
11686  }
11687 
11688  for (const auto *FD : OldFD->redecls()) {
11689  const auto *CurTA = FD->getAttr<TargetAttr>();
11690  const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11691  // We allow forward declarations before ANY multiversioning attributes, but
11692  // nothing after the fact.
11694  ((NewTA && (!CurTA || CurTA->isInherited())) ||
11695  (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11696  S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11697  << (NewTA ? 0 : 2);
11698  S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11699  NewFD->setInvalidDecl();
11700  return true;
11701  }
11702  }
11703 
11704  OldFD->setIsMultiVersion();
11705  NewFD->setIsMultiVersion();
11706  Redeclaration = false;
11707  OldDecl = nullptr;
11708  Previous.clear();
11709  return false;
11710 }
11711 
11713  MultiVersionKind OldKind = Old->getMultiVersionKind();
11714  MultiVersionKind NewKind = New->getMultiVersionKind();
11715 
11716  if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11717  NewKind == MultiVersionKind::None)
11718  return true;
11719 
11720  if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11721  switch (OldKind) {
11723  return NewKind == MultiVersionKind::TargetClones;
11725  return NewKind == MultiVersionKind::TargetVersion;
11726  default:
11727  return false;
11728  }
11729  } else {
11730  switch (OldKind) {
11732  return NewKind == MultiVersionKind::CPUSpecific;
11734  return NewKind == MultiVersionKind::CPUDispatch;
11735  default:
11736  return false;
11737  }
11738  }
11739 }
11740 
11741 /// Check the validity of a new function declaration being added to an existing
11742 /// multiversioned declaration collection.
11744  Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11745  const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11746  const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11748 
11749  // Disallow mixing of multiversioning types.
11750  if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11751  S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11752  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11753  NewFD->setInvalidDecl();
11754  return true;
11755  }
11756 
11757  // Add the default target_version attribute if it's missing.
11758  patchDefaultTargetVersion(OldFD, NewFD);
11759  patchDefaultTargetVersion(NewFD, OldFD);
11760 
11761  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11762  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11763  MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11764  [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11765 
11766  ParsedTargetAttr NewParsed;
11767  if (NewTA) {
11768  NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11769  NewTA->getFeaturesStr());
11770  llvm::sort(NewParsed.Features);
11771  }
11773  if (NewTVA) {
11774  NewTVA->getFeatures(NewFeats);
11775  llvm::sort(NewFeats);
11776  }
11777 
11778  bool UseMemberUsingDeclRules =
11779  S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11780 
11781  bool MayNeedOverloadableChecks =
11783 
11784  // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11785  // of a previous member of the MultiVersion set.
11786  for (NamedDecl *ND : Previous) {
11787  FunctionDecl *CurFD = ND->getAsFunction();
11788  if (!CurFD || CurFD->isInvalidDecl())
11789  continue;
11790  if (MayNeedOverloadableChecks &&
11791  S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11792  continue;
11793 
11794  switch (NewMVKind) {
11796  assert(OldMVKind == MultiVersionKind::TargetClones &&
11797  "Only target_clones can be omitted in subsequent declarations");
11798  break;
11799  case MultiVersionKind::Target: {
11800  const auto *CurTA = CurFD->getAttr<TargetAttr>();
11801  if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11802  NewFD->setIsMultiVersion();
11803  Redeclaration = true;
11804  OldDecl = ND;
11805  return false;
11806  }
11807 
11808  ParsedTargetAttr CurParsed =
11810  CurTA->getFeaturesStr());
11811  llvm::sort(CurParsed.Features);
11812  if (CurParsed == NewParsed) {
11813  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11814  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11815  NewFD->setInvalidDecl();
11816  return true;
11817  }
11818  break;
11819  }
11821  if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11822  if (CurTVA->getName() == NewTVA->getName()) {
11823  NewFD->setIsMultiVersion();
11824  Redeclaration = true;
11825  OldDecl = ND;
11826  return false;
11827  }
11829  CurTVA->getFeatures(CurFeats);
11830  llvm::sort(CurFeats);
11831 
11832  if (CurFeats == NewFeats) {
11833  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11834  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11835  NewFD->setInvalidDecl();
11836  return true;
11837  }
11838  } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11839  // Default
11840  if (NewFeats.empty())
11841  break;
11842 
11843  for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11845  CurClones->getFeatures(CurFeats, I);
11846  llvm::sort(CurFeats);
11847 
11848  if (CurFeats == NewFeats) {
11849  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11850  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11851  NewFD->setInvalidDecl();
11852  return true;
11853  }
11854  }
11855  }
11856  break;
11857  }
11859  assert(NewClones && "MultiVersionKind does not match attribute type");
11860  if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11861  if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11862  !std::equal(CurClones->featuresStrs_begin(),
11863  CurClones->featuresStrs_end(),
11864  NewClones->featuresStrs_begin())) {
11865  S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11866  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11867  NewFD->setInvalidDecl();
11868  return true;
11869  }
11870  } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11872  CurTVA->getFeatures(CurFeats);
11873  llvm::sort(CurFeats);
11874 
11875  // Default
11876  if (CurFeats.empty())
11877  break;
11878 
11879  for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11880  NewFeats.clear();
11881  NewClones->getFeatures(NewFeats, I);
11882  llvm::sort(NewFeats);
11883 
11884  if (CurFeats == NewFeats) {
11885  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11886  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11887  NewFD->setInvalidDecl();
11888  return true;
11889  }
11890  }
11891  break;
11892  }
11893  Redeclaration = true;
11894  OldDecl = CurFD;
11895  NewFD->setIsMultiVersion();
11896  return false;
11897  }
11900  const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11901  const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11902  // Handle CPUDispatch/CPUSpecific versions.
11903  // Only 1 CPUDispatch function is allowed, this will make it go through
11904  // the redeclaration errors.
11905  if (NewMVKind == MultiVersionKind::CPUDispatch &&
11906  CurFD->hasAttr<CPUDispatchAttr>()) {
11907  if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11908  std::equal(
11909  CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11910  NewCPUDisp->cpus_begin(),
11911  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11912  return Cur->getName() == New->getName();
11913  })) {
11914  NewFD->setIsMultiVersion();
11915  Redeclaration = true;
11916  OldDecl = ND;
11917  return false;
11918  }
11919 
11920  // If the declarations don't match, this is an error condition.
11921  S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11922  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11923  NewFD->setInvalidDecl();
11924  return true;
11925  }
11926  if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11927  if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11928  std::equal(
11929  CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11930  NewCPUSpec->cpus_begin(),
11931  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11932  return Cur->getName() == New->getName();
11933  })) {
11934  NewFD->setIsMultiVersion();
11935  Redeclaration = true;
11936  OldDecl = ND;
11937  return false;
11938  }
11939 
11940  // Only 1 version of CPUSpecific is allowed for each CPU.
11941  for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11942  for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11943  if (CurII == NewII) {
11944  S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11945  << NewII;
11946  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11947  NewFD->setInvalidDecl();
11948  return true;
11949  }
11950  }
11951  }
11952  }
11953  break;
11954  }
11955  }
11956  }
11957 
11958  // Else, this is simply a non-redecl case. Checking the 'value' is only
11959  // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11960  // handled in the attribute adding step.
11961  if ((NewMVKind == MultiVersionKind::TargetVersion ||
11962  NewMVKind == MultiVersionKind::Target) &&
11963  CheckMultiVersionValue(S, NewFD)) {
11964  NewFD->setInvalidDecl();
11965  return true;
11966  }
11967 
11968  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11969  !OldFD->isMultiVersion(), NewMVKind)) {
11970  NewFD->setInvalidDecl();
11971  return true;
11972  }
11973 
11974  // Permit forward declarations in the case where these two are compatible.
11975  if (!OldFD->isMultiVersion()) {
11976  OldFD->setIsMultiVersion();
11977  NewFD->setIsMultiVersion();
11978  Redeclaration = true;
11979  OldDecl = OldFD;
11980  return false;
11981  }
11982 
11983  NewFD->setIsMultiVersion();
11984  Redeclaration = false;
11985  OldDecl = nullptr;
11986  Previous.clear();
11987  return false;
11988 }
11989 
11990 /// Check the validity of a mulitversion function declaration.
11991 /// Also sets the multiversion'ness' of the function itself.
11992 ///
11993 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11994 ///
11995 /// Returns true if there was an error, false otherwise.
11997  bool &Redeclaration, NamedDecl *&OldDecl,
11999  const auto *NewTA = NewFD->getAttr<TargetAttr>();
12000  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12001  const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12002  const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12003  const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12004  MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12005 
12006  // Main isn't allowed to become a multiversion function, however it IS
12007  // permitted to have 'main' be marked with the 'target' optimization hint,
12008  // for 'target_version' only default is allowed.
12009  if (NewFD->isMain()) {
12010  if (MVKind != MultiVersionKind::None &&
12011  !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12012  !(MVKind == MultiVersionKind::TargetVersion &&
12013  NewTVA->isDefaultVersion())) {
12014  S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12015  NewFD->setInvalidDecl();
12016  return true;
12017  }
12018  return false;
12019  }
12020 
12021  const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
12022 
12023  // Target attribute on AArch64 is not used for multiversioning
12024  if (NewTA && T.isAArch64())
12025  return false;
12026 
12027  // Target attribute on RISCV is not used for multiversioning
12028  if (NewTA && T.isRISCV())
12029  return false;
12030 
12031  if (!OldDecl || !OldDecl->getAsFunction() ||
12032  OldDecl->getDeclContext()->getRedeclContext() !=
12033  NewFD->getDeclContext()->getRedeclContext()) {
12034  // If there's no previous declaration, AND this isn't attempting to cause
12035  // multiversioning, this isn't an error condition.
12036  if (MVKind == MultiVersionKind::None)
12037  return false;
12038  return CheckMultiVersionFirstFunction(S, NewFD);
12039  }
12040 
12041  FunctionDecl *OldFD = OldDecl->getAsFunction();
12042 
12043  if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
12044  if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
12045  return false;
12046  if (!NewFD->getType()->getAs<FunctionProtoType>()) {
12047  // Multiversion declaration doesn't have prototype.
12048  S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
12049  NewFD->setInvalidDecl();
12050  } else {
12051  // No "target_version" attribute is equivalent to "default" attribute.
12052  NewFD->addAttr(TargetVersionAttr::CreateImplicit(
12053  S.Context, "default", NewFD->getSourceRange()));
12054  NewFD->setIsMultiVersion();
12055  OldFD->setIsMultiVersion();
12056  OldDecl = OldFD;
12057  Redeclaration = true;
12058  }
12059  return true;
12060  }
12061 
12062  // Multiversioned redeclarations aren't allowed to omit the attribute, except
12063  // for target_clones and target_version.
12064  if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12067  S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12069  NewFD->setInvalidDecl();
12070  return true;
12071  }
12072 
12073  if (!OldFD->isMultiVersion()) {
12074  switch (MVKind) {
12077  return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
12078  OldDecl, Previous);
12080  if (OldFD->isUsed(false)) {
12081  NewFD->setInvalidDecl();
12082  return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12083  }
12084  OldFD->setIsMultiVersion();
12085  break;
12086 
12090  break;
12091  }
12092  }
12093 
12094  // At this point, we have a multiversion function decl (in OldFD) AND an
12095  // appropriate attribute in the current function decl. Resolve that these are
12096  // still compatible with previous declarations.
12097  return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12098  NewCPUSpec, NewClones, Redeclaration,
12099  OldDecl, Previous);
12100 }
12101 
12103  bool IsPure = NewFD->hasAttr<PureAttr>();
12104  bool IsConst = NewFD->hasAttr<ConstAttr>();
12105 
12106  // If there are no pure or const attributes, there's nothing to check.
12107  if (!IsPure && !IsConst)
12108  return;
12109 
12110  // If the function is marked both pure and const, we retain the const
12111  // attribute because it makes stronger guarantees than the pure attribute, and
12112  // we drop the pure attribute explicitly to prevent later confusion about
12113  // semantics.
12114  if (IsPure && IsConst) {
12115  S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12116  NewFD->dropAttrs<PureAttr>();
12117  }
12118 
12119  // Constructors and destructors are functions which return void, so are
12120  // handled here as well.
12121  if (NewFD->getReturnType()->isVoidType()) {
12122  S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12123  << IsConst;
12124  NewFD->dropAttrs<PureAttr, ConstAttr>();
12125  }
12126 }
12127 
12128 /// Perform semantic checking of a new function declaration.
12129 ///
12130 /// Performs semantic analysis of the new function declaration
12131 /// NewFD. This routine performs all semantic checking that does not
12132 /// require the actual declarator involved in the declaration, and is
12133 /// used both for the declaration of functions as they are parsed
12134 /// (called via ActOnDeclarator) and for the declaration of functions
12135 /// that have been instantiated via C++ template instantiation (called
12136 /// via InstantiateDecl).
12137 ///
12138 /// \param IsMemberSpecialization whether this new function declaration is
12139 /// a member specialization (that replaces any definition provided by the
12140 /// previous declaration).
12141 ///
12142 /// This sets NewFD->isInvalidDecl() to true if there was an error.
12143 ///
12144 /// \returns true if the function declaration is a redeclaration.
12147  bool IsMemberSpecialization,
12148  bool DeclIsDefn) {
12149  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12150  "Variably modified return types are not handled here");
12151 
12152  // Determine whether the type of this function should be merged with
12153  // a previous visible declaration. This never happens for functions in C++,
12154  // and always happens in C if the previous declaration was visible.
12155  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12156  !Previous.isShadowed();
12157 
12158  bool Redeclaration = false;
12159  NamedDecl *OldDecl = nullptr;
12160  bool MayNeedOverloadableChecks = false;
12161 
12162  // Merge or overload the declaration with an existing declaration of
12163  // the same name, if appropriate.
12164  if (!Previous.empty()) {
12165  // Determine whether NewFD is an overload of PrevDecl or
12166  // a declaration that requires merging. If it's an overload,
12167  // there's no more work to do here; we'll just add the new
12168  // function to the scope.
12169  if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
12170  NamedDecl *Candidate = Previous.getRepresentativeDecl();
12171  if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12172  Redeclaration = true;
12173  OldDecl = Candidate;
12174  }
12175  } else {
12176  MayNeedOverloadableChecks = true;
12177  switch (CheckOverload(S, NewFD, Previous, OldDecl,
12178  /*NewIsUsingDecl*/ false)) {
12179  case Ovl_Match:
12180  Redeclaration = true;
12181  break;
12182 
12183  case Ovl_NonFunction:
12184  Redeclaration = true;
12185  break;
12186 
12187  case Ovl_Overload:
12188  Redeclaration = false;
12189  break;
12190  }
12191  }
12192  }
12193 
12194  // Check for a previous extern "C" declaration with this name.
12195  if (!Redeclaration &&
12197  if (!Previous.empty()) {
12198  // This is an extern "C" declaration with the same name as a previous
12199  // declaration, and thus redeclares that entity...
12200  Redeclaration = true;
12201  OldDecl = Previous.getFoundDecl();
12202  MergeTypeWithPrevious = false;
12203 
12204  // ... except in the presence of __attribute__((overloadable)).
12205  if (OldDecl->hasAttr<OverloadableAttr>() ||
12206  NewFD->hasAttr<OverloadableAttr>()) {
12207  if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12208  MayNeedOverloadableChecks = true;
12209  Redeclaration = false;
12210  OldDecl = nullptr;
12211  }
12212  }
12213  }
12214  }
12215 
12216  if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12217  return Redeclaration;
12218 
12219  // PPC MMA non-pointer types are not allowed as function return types.
12220  if (Context.getTargetInfo().getTriple().isPPC64() &&
12221  CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12222  NewFD->setInvalidDecl();
12223  }
12224 
12225  CheckConstPureAttributesUsage(*this, NewFD);
12226 
12227  // C++ [dcl.spec.auto.general]p12:
12228  // Return type deduction for a templated function with a placeholder in its
12229  // declared type occurs when the definition is instantiated even if the
12230  // function body contains a return statement with a non-type-dependent
12231  // operand.
12232  //
12233  // C++ [temp.dep.expr]p3:
12234  // An id-expression is type-dependent if it is a template-id that is not a
12235  // concept-id and is dependent; or if its terminal name is:
12236  // - [...]
12237  // - associated by name lookup with one or more declarations of member
12238  // functions of a class that is the current instantiation declared with a
12239  // return type that contains a placeholder type,
12240  // - [...]
12241  //
12242  // If this is a templated function with a placeholder in its return type,
12243  // make the placeholder type dependent since it won't be deduced until the
12244  // definition is instantiated. We do this here because it needs to happen
12245  // for implicitly instantiated member functions/member function templates.
12246  if (getLangOpts().CPlusPlus14 &&
12247  (NewFD->isDependentContext() &&
12248  NewFD->getReturnType()->isUndeducedType())) {
12249  const FunctionProtoType *FPT =
12250  NewFD->getType()->castAs<FunctionProtoType>();
12251  QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12252  NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12253  FPT->getExtProtoInfo()));
12254  }
12255 
12256  // C++11 [dcl.constexpr]p8:
12257  // A constexpr specifier for a non-static member function that is not
12258  // a constructor declares that member function to be const.
12259  //
12260  // This needs to be delayed until we know whether this is an out-of-line
12261  // definition of a static member function.
12262  //
12263  // This rule is not present in C++1y, so we produce a backwards
12264  // compatibility warning whenever it happens in C++11.
12265  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12266  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12267  !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12268  !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12269  CXXMethodDecl *OldMD = nullptr;
12270  if (OldDecl)
12271  OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12272  if (!OldMD || !OldMD->isStatic()) {
12273  const FunctionProtoType *FPT =
12274  MD->getType()->castAs<FunctionProtoType>();
12276  EPI.TypeQuals.addConst();
12277  MD->setType(Context.getFunctionType(FPT->getReturnType(),
12278  FPT->getParamTypes(), EPI));
12279 
12280  // Warn that we did this, if we're not performing template instantiation.
12281  // In that case, we'll have warned already when the template was defined.
12282  if (!inTemplateInstantiation()) {
12283  SourceLocation AddConstLoc;
12284  if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12286  AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12287 
12288  Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12289  << FixItHint::CreateInsertion(AddConstLoc, " const");
12290  }
12291  }
12292  }
12293 
12294  if (Redeclaration) {
12295  // NewFD and OldDecl represent declarations that need to be
12296  // merged.
12297  if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12298  DeclIsDefn)) {
12299  NewFD->setInvalidDecl();
12300  return Redeclaration;
12301  }
12302 
12303  Previous.clear();
12304  Previous.addDecl(OldDecl);
12305 
12306  if (FunctionTemplateDecl *OldTemplateDecl =
12307  dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12308  auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12309  FunctionTemplateDecl *NewTemplateDecl
12310  = NewFD->getDescribedFunctionTemplate();
12311  assert(NewTemplateDecl && "Template/non-template mismatch");
12312 
12313  // The call to MergeFunctionDecl above may have created some state in
12314  // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12315  // can add it as a redeclaration.
12316  NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12317 
12318  NewFD->setPreviousDeclaration(OldFD);
12319  if (NewFD->isCXXClassMember()) {
12320  NewFD->setAccess(OldTemplateDecl->getAccess());
12321  NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12322  }
12323 
12324  // If this is an explicit specialization of a member that is a function
12325  // template, mark it as a member specialization.
12326  if (IsMemberSpecialization &&
12327  NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12328  NewTemplateDecl->setMemberSpecialization();
12329  assert(OldTemplateDecl->isMemberSpecialization());
12330  // Explicit specializations of a member template do not inherit deleted
12331  // status from the parent member template that they are specializing.
12332  if (OldFD->isDeleted()) {
12333  // FIXME: This assert will not hold in the presence of modules.
12334  assert(OldFD->getCanonicalDecl() == OldFD);
12335  // FIXME: We need an update record for this AST mutation.
12336  OldFD->setDeletedAsWritten(false);
12337  }
12338  }
12339 
12340  } else {
12341  if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12342  auto *OldFD = cast<FunctionDecl>(OldDecl);
12343  // This needs to happen first so that 'inline' propagates.
12344  NewFD->setPreviousDeclaration(OldFD);
12345  if (NewFD->isCXXClassMember())
12346  NewFD->setAccess(OldFD->getAccess());
12347  }
12348  }
12349  } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12350  !NewFD->getAttr<OverloadableAttr>()) {
12351  assert((Previous.empty() ||
12352  llvm::any_of(Previous,
12353  [](const NamedDecl *ND) {
12354  return ND->hasAttr<OverloadableAttr>();
12355  })) &&
12356  "Non-redecls shouldn't happen without overloadable present");
12357 
12358  auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12359  const auto *FD = dyn_cast<FunctionDecl>(ND);
12360  return FD && !FD->hasAttr<OverloadableAttr>();
12361  });
12362 
12363  if (OtherUnmarkedIter != Previous.end()) {
12364  Diag(NewFD->getLocation(),
12365  diag::err_attribute_overloadable_multiple_unmarked_overloads);
12366  Diag((*OtherUnmarkedIter)->getLocation(),
12367  diag::note_attribute_overloadable_prev_overload)
12368  << false;
12369 
12370  NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12371  }
12372  }
12373 
12374  if (LangOpts.OpenMP)
12375  OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12376 
12377  // Semantic checking for this function declaration (in isolation).
12378 
12379  if (getLangOpts().CPlusPlus) {
12380  // C++-specific checks.
12381  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12382  CheckConstructor(Constructor);
12383  } else if (CXXDestructorDecl *Destructor =
12384  dyn_cast<CXXDestructorDecl>(NewFD)) {
12385  // We check here for invalid destructor names.
12386  // If we have a friend destructor declaration that is dependent, we can't
12387  // diagnose right away because cases like this are still valid:
12388  // template <class T> struct A { friend T::X::~Y(); };
12389  // struct B { struct Y { ~Y(); }; using X = Y; };
12390  // template struct A<B>;
12391  if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12392  !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12393  CXXRecordDecl *Record = Destructor->getParent();
12394  QualType ClassType = Context.getTypeDeclType(Record);
12395 
12397  Context.getCanonicalType(ClassType));
12398  if (NewFD->getDeclName() != Name) {
12399  Diag(NewFD->getLocation(), diag::err_destructor_name);
12400  NewFD->setInvalidDecl();
12401  return Redeclaration;
12402  }
12403  }
12404  } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12405  if (auto *TD = Guide->getDescribedFunctionTemplate())
12406  CheckDeductionGuideTemplate(TD);
12407 
12408  // A deduction guide is not on the list of entities that can be
12409  // explicitly specialized.
12410  if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12411  Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12412  << /*explicit specialization*/ 1;
12413  }
12414 
12415  // Find any virtual functions that this function overrides.
12416  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12417  if (!Method->isFunctionTemplateSpecialization() &&
12418  !Method->getDescribedFunctionTemplate() &&
12419  Method->isCanonicalDecl()) {
12420  AddOverriddenMethods(Method->getParent(), Method);
12421  }
12422  if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12423  // C++2a [class.virtual]p6
12424  // A virtual method shall not have a requires-clause.
12426  diag::err_constrained_virtual_method);
12427 
12428  if (Method->isStatic())
12429  checkThisInStaticMemberFunctionType(Method);
12430  }
12431 
12432  if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12433  ActOnConversionDeclarator(Conversion);
12434 
12435  // Extra checking for C++ overloaded operators (C++ [over.oper]).
12436  if (NewFD->isOverloadedOperator() &&
12437  CheckOverloadedOperatorDeclaration(NewFD)) {
12438  NewFD->setInvalidDecl();
12439  return Redeclaration;
12440  }
12441 
12442  // Extra checking for C++0x literal operators (C++0x [over.literal]).
12443  if (NewFD->getLiteralIdentifier() &&
12444  CheckLiteralOperatorDeclaration(NewFD)) {
12445  NewFD->setInvalidDecl();
12446  return Redeclaration;
12447  }
12448 
12449  // In C++, check default arguments now that we have merged decls. Unless
12450  // the lexical context is the class, because in this case this is done
12451  // during delayed parsing anyway.
12452  if (!CurContext->isRecord())
12453  CheckCXXDefaultArguments(NewFD);
12454 
12455  // If this function is declared as being extern "C", then check to see if
12456  // the function returns a UDT (class, struct, or union type) that is not C
12457  // compatible, and if it does, warn the user.
12458  // But, issue any diagnostic on the first declaration only.
12459  if (Previous.empty() && NewFD->isExternC()) {
12460  QualType R = NewFD->getReturnType();
12461  if (R->isIncompleteType() && !R->isVoidType())
12462  Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12463  << NewFD << R;
12464  else if (!R.isPODType(Context) && !R->isVoidType() &&
12466  Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12467  }
12468 
12469  // C++1z [dcl.fct]p6:
12470  // [...] whether the function has a non-throwing exception-specification
12471  // [is] part of the function type
12472  //
12473  // This results in an ABI break between C++14 and C++17 for functions whose
12474  // declared type includes an exception-specification in a parameter or
12475  // return type. (Exception specifications on the function itself are OK in
12476  // most cases, and exception specifications are not permitted in most other
12477  // contexts where they could make it into a mangling.)
12478  if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12479  auto HasNoexcept = [&](QualType T) -> bool {
12480  // Strip off declarator chunks that could be between us and a function
12481  // type. We don't need to look far, exception specifications are very
12482  // restricted prior to C++17.
12483  if (auto *RT = T->getAs<ReferenceType>())
12484  T = RT->getPointeeType();
12485  else if (T->isAnyPointerType())
12486  T = T->getPointeeType();
12487  else if (auto *MPT = T->getAs<MemberPointerType>())
12488  T = MPT->getPointeeType();
12489  if (auto *FPT = T->getAs<FunctionProtoType>())
12490  if (FPT->isNothrow())
12491  return true;
12492  return false;
12493  };
12494 
12495  auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12496  bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12497  for (QualType T : FPT->param_types())
12498  AnyNoexcept |= HasNoexcept(T);
12499  if (AnyNoexcept)
12500  Diag(NewFD->getLocation(),
12501  diag::warn_cxx17_compat_exception_spec_in_signature)
12502  << NewFD;
12503  }
12504 
12505  if (!Redeclaration && LangOpts.CUDA)
12506  CUDA().checkTargetOverload(NewFD, Previous);
12507  }
12508 
12509  // Check if the function definition uses any AArch64 SME features without
12510  // having the '+sme' feature enabled and warn user if sme locally streaming
12511  // function returns or uses arguments with VL-based types.
12512  if (DeclIsDefn) {
12513  const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12514  bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12515  bool UsesZA = Attr && Attr->isNewZA();
12516  bool UsesZT0 = Attr && Attr->isNewZT0();
12517 
12518  if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12519  if (NewFD->getReturnType()->isSizelessVectorType())
12520  Diag(NewFD->getLocation(),
12521  diag::warn_sme_locally_streaming_has_vl_args_returns)
12522  << /*IsArg=*/false;
12523  if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12524  return P->getOriginalType()->isSizelessVectorType();
12525  }))
12526  Diag(NewFD->getLocation(),
12527  diag::warn_sme_locally_streaming_has_vl_args_returns)
12528  << /*IsArg=*/true;
12529  }
12530  if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12531  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12532  UsesSM |=
12538  }
12539 
12540  if (UsesSM || UsesZA) {
12541  llvm::StringMap<bool> FeatureMap;
12542  Context.getFunctionFeatureMap(FeatureMap, NewFD);
12543  if (!FeatureMap.contains("sme")) {
12544  if (UsesSM)
12545  Diag(NewFD->getLocation(),
12546  diag::err_sme_definition_using_sm_in_non_sme_target);
12547  else
12548  Diag(NewFD->getLocation(),
12549  diag::err_sme_definition_using_za_in_non_sme_target);
12550  }
12551  }
12552  if (UsesZT0) {
12553  llvm::StringMap<bool> FeatureMap;
12554  Context.getFunctionFeatureMap(FeatureMap, NewFD);
12555  if (!FeatureMap.contains("sme2")) {
12556  Diag(NewFD->getLocation(),
12557  diag::err_sme_definition_using_zt0_in_non_sme2_target);
12558  }
12559  }
12560  }
12561 
12562  return Redeclaration;
12563 }
12564 
12565 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12566  // C++11 [basic.start.main]p3:
12567  // A program that [...] declares main to be inline, static or
12568  // constexpr is ill-formed.
12569  // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12570  // appear in a declaration of main.
12571  // static main is not an error under C99, but we should warn about it.
12572  // We accept _Noreturn main as an extension.
12573  if (FD->getStorageClass() == SC_Static)
12574  Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12575  ? diag::err_static_main : diag::warn_static_main)
12577  if (FD->isInlineSpecified())
12578  Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12580  if (DS.isNoreturnSpecified()) {
12581  SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12582  SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12583  Diag(NoreturnLoc, diag::ext_noreturn_main);
12584  Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12585  << FixItHint::CreateRemoval(NoreturnRange);
12586  }
12587  if (FD->isConstexpr()) {
12588  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12589  << FD->isConsteval()
12592  }
12593 
12594  if (getLangOpts().OpenCL) {
12595  Diag(FD->getLocation(), diag::err_opencl_no_main)
12596  << FD->hasAttr<OpenCLKernelAttr>();
12597  FD->setInvalidDecl();
12598  return;
12599  }
12600 
12601  // Functions named main in hlsl are default entries, but don't have specific
12602  // signatures they are required to conform to.
12603  if (getLangOpts().HLSL)
12604  return;
12605 
12606  QualType T = FD->getType();
12607  assert(T->isFunctionType() && "function decl is not of function type");
12608  const FunctionType* FT = T->castAs<FunctionType>();
12609 
12610  // Set default calling convention for main()
12611  if (FT->getCallConv() != CC_C) {
12612  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12613  FD->setType(QualType(FT, 0));
12614  T = Context.getCanonicalType(FD->getType());
12615  }
12616 
12617  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12618  // In C with GNU extensions we allow main() to have non-integer return
12619  // type, but we should warn about the extension, and we disable the
12620  // implicit-return-zero rule.
12621 
12622  // GCC in C mode accepts qualified 'int'.
12623  if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12624  FD->setHasImplicitReturnZero(true);
12625  else {
12626  Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12627  SourceRange RTRange = FD->getReturnTypeSourceRange();
12628  if (RTRange.isValid())
12629  Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12630  << FixItHint::CreateReplacement(RTRange, "int");
12631  }
12632  } else {
12633  // In C and C++, main magically returns 0 if you fall off the end;
12634  // set the flag which tells us that.
12635  // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12636 
12637  // All the standards say that main() should return 'int'.
12638  if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12639  FD->setHasImplicitReturnZero(true);
12640  else {
12641  // Otherwise, this is just a flat-out error.
12642  SourceRange RTRange = FD->getReturnTypeSourceRange();
12643  Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12644  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12645  : FixItHint());
12646  FD->setInvalidDecl(true);
12647  }
12648  }
12649 
12650  // Treat protoless main() as nullary.
12651  if (isa<FunctionNoProtoType>(FT)) return;
12652 
12653  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12654  unsigned nparams = FTP->getNumParams();
12655  assert(FD->getNumParams() == nparams);
12656 
12657  bool HasExtraParameters = (nparams > 3);
12658 
12659  if (FTP->isVariadic()) {
12660  Diag(FD->getLocation(), diag::ext_variadic_main);
12661  // FIXME: if we had information about the location of the ellipsis, we
12662  // could add a FixIt hint to remove it as a parameter.
12663  }
12664 
12665  // Darwin passes an undocumented fourth argument of type char**. If
12666  // other platforms start sprouting these, the logic below will start
12667  // getting shifty.
12668  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12669  HasExtraParameters = false;
12670 
12671  if (HasExtraParameters) {
12672  Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12673  FD->setInvalidDecl(true);
12674  nparams = 3;
12675  }
12676 
12677  // FIXME: a lot of the following diagnostics would be improved
12678  // if we had some location information about types.
12679 
12680  QualType CharPP =
12681  Context.getPointerType(Context.getPointerType(Context.CharTy));
12682  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12683 
12684  for (unsigned i = 0; i < nparams; ++i) {
12685  QualType AT = FTP->getParamType(i);
12686 
12687  bool mismatch = true;
12688 
12689  if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12690  mismatch = false;
12691  else if (Expected[i] == CharPP) {
12692  // As an extension, the following forms are okay:
12693  // char const **
12694  // char const * const *
12695  // char * const *
12696 
12697  QualifierCollector qs;
12698  const PointerType* PT;
12699  if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12700  (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12701  Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12702  Context.CharTy)) {
12703  qs.removeConst();
12704  mismatch = !qs.empty();
12705  }
12706  }
12707 
12708  if (mismatch) {
12709  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12710  // TODO: suggest replacing given type with expected type
12711  FD->setInvalidDecl(true);
12712  }
12713  }
12714 
12715  if (nparams == 1 && !FD->isInvalidDecl()) {
12716  Diag(FD->getLocation(), diag::warn_main_one_arg);
12717  }
12718 
12719  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12720  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12721  FD->setInvalidDecl();
12722  }
12723 }
12724 
12725 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12726 
12727  // Default calling convention for main and wmain is __cdecl
12728  if (FD->getName() == "main" || FD->getName() == "wmain")
12729  return false;
12730 
12731  // Default calling convention for MinGW is __cdecl
12732  const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12733  if (T.isWindowsGNUEnvironment())
12734  return false;
12735 
12736  // Default calling convention for WinMain, wWinMain and DllMain
12737  // is __stdcall on 32 bit Windows
12738  if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12739  return true;
12740 
12741  return false;
12742 }
12743 
12745  QualType T = FD->getType();
12746  assert(T->isFunctionType() && "function decl is not of function type");
12747  const FunctionType *FT = T->castAs<FunctionType>();
12748 
12749  // Set an implicit return of 'zero' if the function can return some integral,
12750  // enumeration, pointer or nullptr type.
12752  FT->getReturnType()->isAnyPointerType() ||
12753  FT->getReturnType()->isNullPtrType())
12754  // DllMain is exempt because a return value of zero means it failed.
12755  if (FD->getName() != "DllMain")
12756  FD->setHasImplicitReturnZero(true);
12757 
12758  // Explicity specified calling conventions are applied to MSVC entry points
12759  if (!hasExplicitCallingConv(T)) {
12760  if (isDefaultStdCall(FD, *this)) {
12761  if (FT->getCallConv() != CC_X86StdCall) {
12762  FT = Context.adjustFunctionType(
12764  FD->setType(QualType(FT, 0));
12765  }
12766  } else if (FT->getCallConv() != CC_C) {
12767  FT = Context.adjustFunctionType(FT,
12769  FD->setType(QualType(FT, 0));
12770  }
12771  }
12772 
12773  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12774  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12775  FD->setInvalidDecl();
12776  }
12777 }
12778 
12780  // FIXME: Need strict checking. In C89, we need to check for
12781  // any assignment, increment, decrement, function-calls, or
12782  // commas outside of a sizeof. In C99, it's the same list,
12783  // except that the aforementioned are allowed in unevaluated
12784  // expressions. Everything else falls under the
12785  // "may accept other forms of constant expressions" exception.
12786  //
12787  // Regular C++ code will not end up here (exceptions: language extensions,
12788  // OpenCL C++ etc), so the constant expression rules there don't matter.
12789  if (Init->isValueDependent()) {
12790  assert(Init->containsErrors() &&
12791  "Dependent code should only occur in error-recovery path.");
12792  return true;
12793  }
12794  const Expr *Culprit;
12795  if (Init->isConstantInitializer(Context, false, &Culprit))
12796  return false;
12797  Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12798  return true;
12799 }
12800 
12801 namespace {
12802  // Visits an initialization expression to see if OrigDecl is evaluated in
12803  // its own initialization and throws a warning if it does.
12804  class SelfReferenceChecker
12805  : public EvaluatedExprVisitor<SelfReferenceChecker> {
12806  Sema &S;
12807  Decl *OrigDecl;
12808  bool isRecordType;
12809  bool isPODType;
12810  bool isReferenceType;
12811 
12812  bool isInitList;
12813  llvm::SmallVector<unsigned, 4> InitFieldIndex;
12814 
12815  public:
12817 
12818  SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12819  S(S), OrigDecl(OrigDecl) {
12820  isPODType = false;
12821  isRecordType = false;
12822  isReferenceType = false;
12823  isInitList = false;
12824  if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12825  isPODType = VD->getType().isPODType(S.Context);
12826  isRecordType = VD->getType()->isRecordType();
12827  isReferenceType = VD->getType()->isReferenceType();
12828  }
12829  }
12830 
12831  // For most expressions, just call the visitor. For initializer lists,
12832  // track the index of the field being initialized since fields are
12833  // initialized in order allowing use of previously initialized fields.
12834  void CheckExpr(Expr *E) {
12835  InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12836  if (!InitList) {
12837  Visit(E);
12838  return;
12839  }
12840 
12841  // Track and increment the index here.
12842  isInitList = true;
12843  InitFieldIndex.push_back(0);
12844  for (auto *Child : InitList->children()) {
12845  CheckExpr(cast<Expr>(Child));
12846  ++InitFieldIndex.back();
12847  }
12848  InitFieldIndex.pop_back();
12849  }
12850 
12851  // Returns true if MemberExpr is checked and no further checking is needed.
12852  // Returns false if additional checking is required.
12853  bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12855  Expr *Base = E;
12856  bool ReferenceField = false;
12857 
12858  // Get the field members used.
12859  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12860  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12861  if (!FD)
12862  return false;
12863  Fields.push_back(FD);
12864  if (FD->getType()->isReferenceType())
12865  ReferenceField = true;
12866  Base = ME->getBase()->IgnoreParenImpCasts();
12867  }
12868 
12869  // Keep checking only if the base Decl is the same.
12870  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12871  if (!DRE || DRE->getDecl() != OrigDecl)
12872  return false;
12873 
12874  // A reference field can be bound to an unininitialized field.
12875  if (CheckReference && !ReferenceField)
12876  return true;
12877 
12878  // Convert FieldDecls to their index number.
12879  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12880  for (const FieldDecl *I : llvm::reverse(Fields))
12881  UsedFieldIndex.push_back(I->getFieldIndex());
12882 
12883  // See if a warning is needed by checking the first difference in index
12884  // numbers. If field being used has index less than the field being
12885  // initialized, then the use is safe.
12886  for (auto UsedIter = UsedFieldIndex.begin(),
12887  UsedEnd = UsedFieldIndex.end(),
12888  OrigIter = InitFieldIndex.begin(),
12889  OrigEnd = InitFieldIndex.end();
12890  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12891  if (*UsedIter < *OrigIter)
12892  return true;
12893  if (*UsedIter > *OrigIter)
12894  break;
12895  }
12896 
12897  // TODO: Add a different warning which will print the field names.
12898  HandleDeclRefExpr(DRE);
12899  return true;
12900  }
12901 
12902  // For most expressions, the cast is directly above the DeclRefExpr.
12903  // For conditional operators, the cast can be outside the conditional
12904  // operator if both expressions are DeclRefExpr's.
12905  void HandleValue(Expr *E) {
12906  E = E->IgnoreParens();
12907  if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12908  HandleDeclRefExpr(DRE);
12909  return;
12910  }
12911 
12912  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12913  Visit(CO->getCond());
12914  HandleValue(CO->getTrueExpr());
12915  HandleValue(CO->getFalseExpr());
12916  return;
12917  }
12918 
12919  if (BinaryConditionalOperator *BCO =
12920  dyn_cast<BinaryConditionalOperator>(E)) {
12921  Visit(BCO->getCond());
12922  HandleValue(BCO->getFalseExpr());
12923  return;
12924  }
12925 
12926  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12927  if (Expr *SE = OVE->getSourceExpr())
12928  HandleValue(SE);
12929  return;
12930  }
12931 
12932  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12933  if (BO->getOpcode() == BO_Comma) {
12934  Visit(BO->getLHS());
12935  HandleValue(BO->getRHS());
12936  return;
12937  }
12938  }
12939 
12940  if (isa<MemberExpr>(E)) {
12941  if (isInitList) {
12942  if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12943  false /*CheckReference*/))
12944  return;
12945  }
12946 
12947  Expr *Base = E->IgnoreParenImpCasts();
12948  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12949  // Check for static member variables and don't warn on them.
12950  if (!isa<FieldDecl>(ME->getMemberDecl()))
12951  return;
12952  Base = ME->getBase()->IgnoreParenImpCasts();
12953  }
12954  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12955  HandleDeclRefExpr(DRE);
12956  return;
12957  }
12958 
12959  Visit(E);
12960  }
12961 
12962  // Reference types not handled in HandleValue are handled here since all
12963  // uses of references are bad, not just r-value uses.
12964  void VisitDeclRefExpr(DeclRefExpr *E) {
12965  if (isReferenceType)
12966  HandleDeclRefExpr(E);
12967  }
12968 
12969  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12970  if (E->getCastKind() == CK_LValueToRValue) {
12971  HandleValue(E->getSubExpr());
12972  return;
12973  }
12974 
12975  Inherited::VisitImplicitCastExpr(E);
12976  }
12977 
12978  void VisitMemberExpr(MemberExpr *E) {
12979  if (isInitList) {
12980  if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12981  return;
12982  }
12983 
12984  // Don't warn on arrays since they can be treated as pointers.
12985  if (E->getType()->canDecayToPointerType()) return;
12986 
12987  // Warn when a non-static method call is followed by non-static member
12988  // field accesses, which is followed by a DeclRefExpr.
12989  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12990  bool Warn = (MD && !MD->isStatic());
12991  Expr *Base = E->getBase()->IgnoreParenImpCasts();
12992  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12993  if (!isa<FieldDecl>(ME->getMemberDecl()))
12994  Warn = false;
12995  Base = ME->getBase()->IgnoreParenImpCasts();
12996  }
12997 
12998  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12999  if (Warn)
13000  HandleDeclRefExpr(DRE);
13001  return;
13002  }
13003 
13004  // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13005  // Visit that expression.
13006  Visit(Base);
13007  }
13008 
13009  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13010  Expr *Callee = E->getCallee();
13011 
13012  if (isa<UnresolvedLookupExpr>(Callee))
13013  return Inherited::VisitCXXOperatorCallExpr(E);
13014 
13015  Visit(Callee);
13016  for (auto Arg: E->arguments())
13017  HandleValue(Arg->IgnoreParenImpCasts());
13018  }
13019 
13020  void VisitUnaryOperator(UnaryOperator *E) {
13021  // For POD record types, addresses of its own members are well-defined.
13022  if (E->getOpcode() == UO_AddrOf && isRecordType &&
13023  isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
13024  if (!isPODType)
13025  HandleValue(E->getSubExpr());
13026  return;
13027  }
13028 
13029  if (E->isIncrementDecrementOp()) {
13030  HandleValue(E->getSubExpr());
13031  return;
13032  }
13033 
13034  Inherited::VisitUnaryOperator(E);
13035  }
13036 
13037  void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13038 
13039  void VisitCXXConstructExpr(CXXConstructExpr *E) {
13040  if (E->getConstructor()->isCopyConstructor()) {
13041  Expr *ArgExpr = E->getArg(0);
13042  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13043  if (ILE->getNumInits() == 1)
13044  ArgExpr = ILE->getInit(0);
13045  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13046  if (ICE->getCastKind() == CK_NoOp)
13047  ArgExpr = ICE->getSubExpr();
13048  HandleValue(ArgExpr);
13049  return;
13050  }
13051  Inherited::VisitCXXConstructExpr(E);
13052  }
13053 
13054  void VisitCallExpr(CallExpr *E) {
13055  // Treat std::move as a use.
13056  if (E->isCallToStdMove()) {
13057  HandleValue(E->getArg(0));
13058  return;
13059  }
13060 
13061  Inherited::VisitCallExpr(E);
13062  }
13063 
13064  void VisitBinaryOperator(BinaryOperator *E) {
13065  if (E->isCompoundAssignmentOp()) {
13066  HandleValue(E->getLHS());
13067  Visit(E->getRHS());
13068  return;
13069  }
13070 
13071  Inherited::VisitBinaryOperator(E);
13072  }
13073 
13074  // A custom visitor for BinaryConditionalOperator is needed because the
13075  // regular visitor would check the condition and true expression separately
13076  // but both point to the same place giving duplicate diagnostics.
13077  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13078  Visit(E->getCond());
13079  Visit(E->getFalseExpr());
13080  }
13081 
13082  void HandleDeclRefExpr(DeclRefExpr *DRE) {
13083  Decl* ReferenceDecl = DRE->getDecl();
13084  if (OrigDecl != ReferenceDecl) return;
13085  unsigned diag;
13086  if (isReferenceType) {
13087  diag = diag::warn_uninit_self_reference_in_reference_init;
13088  } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13089  diag = diag::warn_static_self_reference_in_init;
13090  } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13091  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13092  DRE->getDecl()->getType()->isRecordType()) {
13093  diag = diag::warn_uninit_self_reference_in_init;
13094  } else {
13095  // Local variables will be handled by the CFG analysis.
13096  return;
13097  }
13098 
13099  S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13100  S.PDiag(diag)
13101  << DRE->getDecl() << OrigDecl->getLocation()
13102  << DRE->getSourceRange());
13103  }
13104  };
13105 
13106  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13107  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13108  bool DirectInit) {
13109  // Parameters arguments are occassionially constructed with itself,
13110  // for instance, in recursive functions. Skip them.
13111  if (isa<ParmVarDecl>(OrigDecl))
13112  return;
13113 
13114  E = E->IgnoreParens();
13115 
13116  // Skip checking T a = a where T is not a record or reference type.
13117  // Doing so is a way to silence uninitialized warnings.
13118  if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13119  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13120  if (ICE->getCastKind() == CK_LValueToRValue)
13121  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13122  if (DRE->getDecl() == OrigDecl)
13123  return;
13124 
13125  SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13126  }
13127 } // end anonymous namespace
13128 
13129 namespace {
13130  // Simple wrapper to add the name of a variable or (if no variable is
13131  // available) a DeclarationName into a diagnostic.
13132  struct VarDeclOrName {
13133  VarDecl *VDecl;
13134  DeclarationName Name;
13135 
13136  friend const Sema::SemaDiagnosticBuilder &
13137  operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13138  return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13139  }
13140  };
13141 } // end anonymous namespace
13142 
13145  TypeSourceInfo *TSI,
13146  SourceRange Range, bool DirectInit,
13147  Expr *Init) {
13148  bool IsInitCapture = !VDecl;
13149  assert((!VDecl || !VDecl->isInitCapture()) &&
13150  "init captures are expected to be deduced prior to initialization");
13151 
13152  VarDeclOrName VN{VDecl, Name};
13153 
13155  assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13156 
13157  // Diagnose auto array declarations in C23, unless it's a supported extension.
13158  if (getLangOpts().C23 && Type->isArrayType() &&
13159  !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13160  Diag(Range.getBegin(), diag::err_auto_not_allowed)
13161  << (int)Deduced->getContainedAutoType()->getKeyword()
13162  << /*in array decl*/ 23 << Range;
13163  return QualType();
13164  }
13165 
13166  // C++11 [dcl.spec.auto]p3
13167  if (!Init) {
13168  assert(VDecl && "no init for init capture deduction?");
13169 
13170  // Except for class argument deduction, and then for an initializing
13171  // declaration only, i.e. no static at class scope or extern.
13172  if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
13173  VDecl->hasExternalStorage() ||
13174  VDecl->isStaticDataMember()) {
13175  Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13176  << VDecl->getDeclName() << Type;
13177  return QualType();
13178  }
13179  }
13180 
13181  ArrayRef<Expr*> DeduceInits;
13182  if (Init)
13183  DeduceInits = Init;
13184 
13185  auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13186  if (DirectInit && PL)
13187  DeduceInits = PL->exprs();
13188 
13189  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
13190  assert(VDecl && "non-auto type for init capture deduction?");
13193  VDecl->getLocation(), DirectInit, Init);
13194  // FIXME: Initialization should not be taking a mutable list of inits.
13195  SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
13196  return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13197  InitsCopy);
13198  }
13199 
13200  if (DirectInit) {
13201  if (auto *IL = dyn_cast<InitListExpr>(Init))
13202  DeduceInits = IL->inits();
13203  }
13204 
13205  // Deduction only works if we have exactly one source expression.
13206  if (DeduceInits.empty()) {
13207  // It isn't possible to write this directly, but it is possible to
13208  // end up in this situation with "auto x(some_pack...);"
13209  Diag(Init->getBeginLoc(), IsInitCapture
13210  ? diag::err_init_capture_no_expression
13211  : diag::err_auto_var_init_no_expression)
13212  << VN << Type << Range;
13213  return QualType();
13214  }
13215 
13216  if (DeduceInits.size() > 1) {
13217  Diag(DeduceInits[1]->getBeginLoc(),
13218  IsInitCapture ? diag::err_init_capture_multiple_expressions
13219  : diag::err_auto_var_init_multiple_expressions)
13220  << VN << Type << Range;
13221  return QualType();
13222  }
13223 
13224  Expr *DeduceInit = DeduceInits[0];
13225  if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13226  Diag(Init->getBeginLoc(), IsInitCapture
13227  ? diag::err_init_capture_paren_braces
13228  : diag::err_auto_var_init_paren_braces)
13229  << isa<InitListExpr>(Init) << VN << Type << Range;
13230  return QualType();
13231  }
13232 
13233  // Expressions default to 'id' when we're in a debugger.
13234  bool DefaultedAnyToId = false;
13235  if (getLangOpts().DebuggerCastResultToId &&
13236  Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13237  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13238  if (Result.isInvalid()) {
13239  return QualType();
13240  }
13241  Init = Result.get();
13242  DefaultedAnyToId = true;
13243  }
13244 
13245  // C++ [dcl.decomp]p1:
13246  // If the assignment-expression [...] has array type A and no ref-qualifier
13247  // is present, e has type cv A
13248  if (VDecl && isa<DecompositionDecl>(VDecl) &&
13249  Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13250  DeduceInit->getType()->isConstantArrayType())
13251  return Context.getQualifiedType(DeduceInit->getType(),
13252  Type.getQualifiers());
13253 
13255  TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13256  TemplateDeductionResult Result =
13257  DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13258  if (Result != TemplateDeductionResult::Success &&
13260  if (!IsInitCapture)
13261  DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13262  else if (isa<InitListExpr>(Init))
13263  Diag(Range.getBegin(),
13264  diag::err_init_capture_deduction_failure_from_init_list)
13265  << VN
13266  << (DeduceInit->getType().isNull() ? TSI->getType()
13267  : DeduceInit->getType())
13268  << DeduceInit->getSourceRange();
13269  else
13270  Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13271  << VN << TSI->getType()
13272  << (DeduceInit->getType().isNull() ? TSI->getType()
13273  : DeduceInit->getType())
13274  << DeduceInit->getSourceRange();
13275  }
13276 
13277  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13278  // 'id' instead of a specific object type prevents most of our usual
13279  // checks.
13280  // We only want to warn outside of template instantiations, though:
13281  // inside a template, the 'id' could have come from a parameter.
13282  if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13283  !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13284  SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13285  Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13286  }
13287 
13288  return DeducedType;
13289 }
13290 
13291 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13292  Expr *Init) {
13293  assert(!Init || !Init->containsErrors());
13294  QualType DeducedType = deduceVarTypeFromInitializer(
13295  VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13296  VDecl->getSourceRange(), DirectInit, Init);
13297  if (DeducedType.isNull()) {
13298  VDecl->setInvalidDecl();
13299  return true;
13300  }
13301 
13302  VDecl->setType(DeducedType);
13303  assert(VDecl->isLinkageValid());
13304 
13305  // In ARC, infer lifetime.
13306  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13307  VDecl->setInvalidDecl();
13308 
13309  if (getLangOpts().OpenCL)
13310  deduceOpenCLAddressSpace(VDecl);
13311 
13312  // If this is a redeclaration, check that the type we just deduced matches
13313  // the previously declared type.
13314  if (VarDecl *Old = VDecl->getPreviousDecl()) {
13315  // We never need to merge the type, because we cannot form an incomplete
13316  // array of auto, nor deduce such a type.
13317  MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13318  }
13319 
13320  // Check the deduced type is valid for a variable declaration.
13321  CheckVariableDeclarationType(VDecl);
13322  return VDecl->isInvalidDecl();
13323 }
13324 
13326  SourceLocation Loc) {
13327  if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13328  Init = EWC->getSubExpr();
13329 
13330  if (auto *CE = dyn_cast<ConstantExpr>(Init))
13331  Init = CE->getSubExpr();
13332 
13333  QualType InitType = Init->getType();
13335  InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13336  "shouldn't be called if type doesn't have a non-trivial C struct");
13337  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13338  for (auto *I : ILE->inits()) {
13339  if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13340  !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13341  continue;
13342  SourceLocation SL = I->getExprLoc();
13343  checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13344  }
13345  return;
13346  }
13347 
13348  if (isa<ImplicitValueInitExpr>(Init)) {
13350  checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
13351  NTCUK_Init);
13352  } else {
13353  // Assume all other explicit initializers involving copying some existing
13354  // object.
13355  // TODO: ignore any explicit initializers where we can guarantee
13356  // copy-elision.
13357  if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13358  checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13359  }
13360 }
13361 
13362 namespace {
13363 
13364 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13365  // Ignore unavailable fields. A field can be marked as unavailable explicitly
13366  // in the source code or implicitly by the compiler if it is in a union
13367  // defined in a system header and has non-trivial ObjC ownership
13368  // qualifications. We don't want those fields to participate in determining
13369  // whether the containing union is non-trivial.
13370  return FD->hasAttr<UnavailableAttr>();
13371 }
13372 
13373 struct DiagNonTrivalCUnionDefaultInitializeVisitor
13374  : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13375  void> {
13376  using Super =
13377  DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13378  void>;
13379 
13380  DiagNonTrivalCUnionDefaultInitializeVisitor(
13381  QualType OrigTy, SourceLocation OrigLoc,
13382  Sema::NonTrivialCUnionContext UseContext, Sema &S)
13383  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13384 
13385  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13386  const FieldDecl *FD, bool InNonTrivialUnion) {
13387  if (const auto *AT = S.Context.getAsArrayType(QT))
13388  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13389  InNonTrivialUnion);
13390  return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13391  }
13392 
13393  void visitARCStrong(QualType QT, const FieldDecl *FD,
13394  bool InNonTrivialUnion) {
13395  if (InNonTrivialUnion)
13396  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13397  << 1 << 0 << QT << FD->getName();
13398  }
13399 
13400  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13401  if (InNonTrivialUnion)
13402  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13403  << 1 << 0 << QT << FD->getName();
13404  }
13405 
13406  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13407  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13408  if (RD->isUnion()) {
13409  if (OrigLoc.isValid()) {
13410  bool IsUnion = false;
13411  if (auto *OrigRD = OrigTy->getAsRecordDecl())
13412  IsUnion = OrigRD->isUnion();
13413  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13414  << 0 << OrigTy << IsUnion << UseContext;
13415  // Reset OrigLoc so that this diagnostic is emitted only once.
13416  OrigLoc = SourceLocation();
13417  }
13418  InNonTrivialUnion = true;
13419  }
13420 
13421  if (InNonTrivialUnion)
13422  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13423  << 0 << 0 << QT.getUnqualifiedType() << "";
13424 
13425  for (const FieldDecl *FD : RD->fields())
13426  if (!shouldIgnoreForRecordTriviality(FD))
13427  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13428  }
13429 
13430  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13431 
13432  // The non-trivial C union type or the struct/union type that contains a
13433  // non-trivial C union.
13434  QualType OrigTy;
13435  SourceLocation OrigLoc;
13436  Sema::NonTrivialCUnionContext UseContext;
13437  Sema &S;
13438 };
13439 
13440 struct DiagNonTrivalCUnionDestructedTypeVisitor
13441  : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13442  using Super =
13444 
13445  DiagNonTrivalCUnionDestructedTypeVisitor(
13446  QualType OrigTy, SourceLocation OrigLoc,
13447  Sema::NonTrivialCUnionContext UseContext, Sema &S)
13448  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13449 
13450  void visitWithKind(QualType::DestructionKind DK, QualType QT,
13451  const FieldDecl *FD, bool InNonTrivialUnion) {
13452  if (const auto *AT = S.Context.getAsArrayType(QT))
13453  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13454  InNonTrivialUnion);
13455  return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13456  }
13457 
13458  void visitARCStrong(QualType QT, const FieldDecl *FD,
13459  bool InNonTrivialUnion) {
13460  if (InNonTrivialUnion)
13461  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13462  << 1 << 1 << QT << FD->getName();
13463  }
13464 
13465  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13466  if (InNonTrivialUnion)
13467  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13468  << 1 << 1 << QT << FD->getName();
13469  }
13470 
13471  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13472  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13473  if (RD->isUnion()) {
13474  if (OrigLoc.isValid()) {
13475  bool IsUnion = false;
13476  if (auto *OrigRD = OrigTy->getAsRecordDecl())
13477  IsUnion = OrigRD->isUnion();
13478  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13479  << 1 << OrigTy << IsUnion << UseContext;
13480  // Reset OrigLoc so that this diagnostic is emitted only once.
13481  OrigLoc = SourceLocation();
13482  }
13483  InNonTrivialUnion = true;
13484  }
13485 
13486  if (InNonTrivialUnion)
13487  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13488  << 0 << 1 << QT.getUnqualifiedType() << "";
13489 
13490  for (const FieldDecl *FD : RD->fields())
13491  if (!shouldIgnoreForRecordTriviality(FD))
13492  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13493  }
13494 
13495  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13496  void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13497  bool InNonTrivialUnion) {}
13498 
13499  // The non-trivial C union type or the struct/union type that contains a
13500  // non-trivial C union.
13501  QualType OrigTy;
13502  SourceLocation OrigLoc;
13503  Sema::NonTrivialCUnionContext UseContext;
13504  Sema &S;
13505 };
13506 
13507 struct DiagNonTrivalCUnionCopyVisitor
13508  : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13510 
13511  DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13512  Sema::NonTrivialCUnionContext UseContext,
13513  Sema &S)
13514  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13515 
13516  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13517  const FieldDecl *FD, bool InNonTrivialUnion) {
13518  if (const auto *AT = S.Context.getAsArrayType(QT))
13519  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13520  InNonTrivialUnion);
13521  return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13522  }
13523 
13524  void visitARCStrong(QualType QT, const FieldDecl *FD,
13525  bool InNonTrivialUnion) {
13526  if (InNonTrivialUnion)
13527  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13528  << 1 << 2 << QT << FD->getName();
13529  }
13530 
13531  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13532  if (InNonTrivialUnion)
13533  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13534  << 1 << 2 << QT << FD->getName();
13535  }
13536 
13537  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13538  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13539  if (RD->isUnion()) {
13540  if (OrigLoc.isValid()) {
13541  bool IsUnion = false;
13542  if (auto *OrigRD = OrigTy->getAsRecordDecl())
13543  IsUnion = OrigRD->isUnion();
13544  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13545  << 2 << OrigTy << IsUnion << UseContext;
13546  // Reset OrigLoc so that this diagnostic is emitted only once.
13547  OrigLoc = SourceLocation();
13548  }
13549  InNonTrivialUnion = true;
13550  }
13551 
13552  if (InNonTrivialUnion)
13553  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13554  << 0 << 2 << QT.getUnqualifiedType() << "";
13555 
13556  for (const FieldDecl *FD : RD->fields())
13557  if (!shouldIgnoreForRecordTriviality(FD))
13558  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13559  }
13560 
13561  void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13562  const FieldDecl *FD, bool InNonTrivialUnion) {}
13563  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13564  void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13565  bool InNonTrivialUnion) {}
13566 
13567  // The non-trivial C union type or the struct/union type that contains a
13568  // non-trivial C union.
13569  QualType OrigTy;
13570  SourceLocation OrigLoc;
13571  Sema::NonTrivialCUnionContext UseContext;
13572  Sema &S;
13573 };
13574 
13575 } // namespace
13576 
13578  NonTrivialCUnionContext UseContext,
13579  unsigned NonTrivialKind) {
13583  "shouldn't be called if type doesn't have a non-trivial C union");
13584 
13585  if ((NonTrivialKind & NTCUK_Init) &&
13587  DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13588  .visit(QT, nullptr, false);
13589  if ((NonTrivialKind & NTCUK_Destruct) &&
13591  DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13592  .visit(QT, nullptr, false);
13593  if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13594  DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13595  .visit(QT, nullptr, false);
13596 }
13597 
13598 /// AddInitializerToDecl - Adds the initializer Init to the
13599 /// declaration dcl. If DirectInit is true, this is C++ direct
13600 /// initialization rather than copy initialization.
13601 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13602  // If there is no declaration, there was an error parsing it. Just ignore
13603  // the initializer.
13604  if (!RealDecl || RealDecl->isInvalidDecl()) {
13605  CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13606  return;
13607  }
13608 
13609  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13610  // Pure-specifiers are handled in ActOnPureSpecifier.
13611  Diag(Method->getLocation(), diag::err_member_function_initialization)
13612  << Method->getDeclName() << Init->getSourceRange();
13613  Method->setInvalidDecl();
13614  return;
13615  }
13616 
13617  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13618  if (!VDecl) {
13619  assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13620  Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13621  RealDecl->setInvalidDecl();
13622  return;
13623  }
13624 
13625  // WebAssembly tables can't be used to initialise a variable.
13626  if (Init && !Init->getType().isNull() &&
13627  Init->getType()->isWebAssemblyTableType()) {
13628  Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13629  VDecl->setInvalidDecl();
13630  return;
13631  }
13632 
13633  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13634  if (VDecl->getType()->isUndeducedType()) {
13635  // Attempt typo correction early so that the type of the init expression can
13636  // be deduced based on the chosen correction if the original init contains a
13637  // TypoExpr.
13638  ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13639  if (!Res.isUsable()) {
13640  // There are unresolved typos in Init, just drop them.
13641  // FIXME: improve the recovery strategy to preserve the Init.
13642  RealDecl->setInvalidDecl();
13643  return;
13644  }
13645  if (Res.get()->containsErrors()) {
13646  // Invalidate the decl as we don't know the type for recovery-expr yet.
13647  RealDecl->setInvalidDecl();
13648  VDecl->setInit(Res.get());
13649  return;
13650  }
13651  Init = Res.get();
13652 
13653  if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13654  return;
13655  }
13656 
13657  // dllimport cannot be used on variable definitions.
13658  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13659  Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13660  VDecl->setInvalidDecl();
13661  return;
13662  }
13663 
13664  // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13665  // the identifier has external or internal linkage, the declaration shall
13666  // have no initializer for the identifier.
13667  // C++14 [dcl.init]p5 is the same restriction for C++.
13668  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13669  Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13670  VDecl->setInvalidDecl();
13671  return;
13672  }
13673 
13674  if (!VDecl->getType()->isDependentType()) {
13675  // A definition must end up with a complete type, which means it must be
13676  // complete with the restriction that an array type might be completed by
13677  // the initializer; note that later code assumes this restriction.
13678  QualType BaseDeclType = VDecl->getType();
13679  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13680  BaseDeclType = Array->getElementType();
13681  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13682  diag::err_typecheck_decl_incomplete_type)) {
13683  RealDecl->setInvalidDecl();
13684  return;
13685  }
13686 
13687  // The variable can not have an abstract class type.
13688  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13689  diag::err_abstract_type_in_decl,
13690  AbstractVariableType))
13691  VDecl->setInvalidDecl();
13692  }
13693 
13694  // C++ [module.import/6] external definitions are not permitted in header
13695  // units.
13696  if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13697  !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13698  VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13699  !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13700  Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13701  VDecl->setInvalidDecl();
13702  }
13703 
13704  // If adding the initializer will turn this declaration into a definition,
13705  // and we already have a definition for this variable, diagnose or otherwise
13706  // handle the situation.
13707  if (VarDecl *Def = VDecl->getDefinition())
13708  if (Def != VDecl &&
13709  (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13711  checkVarDeclRedefinition(Def, VDecl))
13712  return;
13713 
13714  if (getLangOpts().CPlusPlus) {
13715  // C++ [class.static.data]p4
13716  // If a static data member is of const integral or const
13717  // enumeration type, its declaration in the class definition can
13718  // specify a constant-initializer which shall be an integral
13719  // constant expression (5.19). In that case, the member can appear
13720  // in integral constant expressions. The member shall still be
13721  // defined in a namespace scope if it is used in the program and the
13722  // namespace scope definition shall not contain an initializer.
13723  //
13724  // We already performed a redefinition check above, but for static
13725  // data members we also need to check whether there was an in-class
13726  // declaration with an initializer.
13727  if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13728  Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13729  << VDecl->getDeclName();
13730  Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13731  diag::note_previous_initializer)
13732  << 0;
13733  return;
13734  }
13735 
13736  if (VDecl->hasLocalStorage())
13737  setFunctionHasBranchProtectedScope();
13738 
13739  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13740  VDecl->setInvalidDecl();
13741  return;
13742  }
13743  }
13744 
13745  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13746  // a kernel function cannot be initialized."
13747  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13748  Diag(VDecl->getLocation(), diag::err_local_cant_init);
13749  VDecl->setInvalidDecl();
13750  return;
13751  }
13752  // In the SYCL explicit SIMD extension non constant "private globals" can't
13753  // be explicitly initialized in the declaration.
13754  if (SYCL().isSYCLEsimdPrivateGlobal(VDecl)) {
13755  Diag(VDecl->getLocation(), diag::err_esimd_glob_cant_init);
13756  VDecl->setInvalidDecl();
13757  return;
13758  }
13759 
13760  // The LoaderUninitialized attribute acts as a definition (of undef).
13761  if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13762  Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13763  VDecl->setInvalidDecl();
13764  return;
13765  }
13766 
13767  // Get the decls type and save a reference for later, since
13768  // CheckInitializerTypes may change it.
13769  QualType DclT = VDecl->getType(), SavT = DclT;
13770 
13771  // Expressions default to 'id' when we're in a debugger
13772  // and we are assigning it to a variable of Objective-C pointer type.
13773  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13774  Init->getType() == Context.UnknownAnyTy) {
13775  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13776  if (Result.isInvalid()) {
13777  VDecl->setInvalidDecl();
13778  return;
13779  }
13780  Init = Result.get();
13781  }
13782 
13783  // Perform the initialization.
13784  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13785  bool IsParenListInit = false;
13786  if (!VDecl->isInvalidDecl()) {
13789  VDecl->getLocation(), DirectInit, Init);
13790 
13791  MultiExprArg Args = Init;
13792  if (CXXDirectInit)
13793  Args = MultiExprArg(CXXDirectInit->getExprs(),
13794  CXXDirectInit->getNumExprs());
13795 
13796  // Try to correct any TypoExprs in the initialization arguments.
13797  for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13798  ExprResult Res = CorrectDelayedTyposInExpr(
13799  Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13800  [this, Entity, Kind](Expr *E) {
13801  InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13802  return Init.Failed() ? ExprError() : E;
13803  });
13804  if (Res.isInvalid()) {
13805  VDecl->setInvalidDecl();
13806  } else if (Res.get() != Args[Idx]) {
13807  Args[Idx] = Res.get();
13808  }
13809  }
13810  if (VDecl->isInvalidDecl())
13811  return;
13812 
13813  InitializationSequence InitSeq(*this, Entity, Kind, Args,
13814  /*TopLevelOfInitList=*/false,
13815  /*TreatUnavailableAsInvalid=*/false);
13816  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13817  if (Result.isInvalid()) {
13818  // If the provided initializer fails to initialize the var decl,
13819  // we attach a recovery expr for better recovery.
13820  auto RecoveryExpr =
13821  CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13822  if (RecoveryExpr.get())
13823  VDecl->setInit(RecoveryExpr.get());
13824  // In general, for error recovery purposes, the initalizer doesn't play
13825  // part in the valid bit of the declaration. There are a few exceptions:
13826  // 1) if the var decl has a deduced auto type, and the type cannot be
13827  // deduced by an invalid initializer;
13828  // 2) if the var decl is decompsition decl with a non-deduced type, and
13829  // the initialization fails (e.g. `int [a] = {1, 2};`);
13830  // Case 1) was already handled elsewhere.
13831  if (isa<DecompositionDecl>(VDecl)) // Case 2)
13832  VDecl->setInvalidDecl();
13833  return;
13834  }
13835 
13836  Init = Result.getAs<Expr>();
13837  IsParenListInit = !InitSeq.steps().empty() &&
13838  InitSeq.step_begin()->Kind ==
13840  QualType VDeclType = VDecl->getType();
13841  if (Init && !Init->getType().isNull() &&
13842  !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13843  Context.getAsIncompleteArrayType(VDeclType) &&
13844  Context.getAsIncompleteArrayType(Init->getType())) {
13845  // Bail out if it is not possible to deduce array size from the
13846  // initializer.
13847  Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13848  << VDeclType;
13849  VDecl->setInvalidDecl();
13850  return;
13851  }
13852  }
13853 
13854  // Check for self-references within variable initializers.
13855  // Variables declared within a function/method body (except for references)
13856  // are handled by a dataflow analysis.
13857  // This is undefined behavior in C++, but valid in C.
13858  if (getLangOpts().CPlusPlus)
13859  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13860  VDecl->getType()->isReferenceType())
13861  CheckSelfReference(*this, RealDecl, Init, DirectInit);
13862 
13863  // If the type changed, it means we had an incomplete type that was
13864  // completed by the initializer. For example:
13865  // int ary[] = { 1, 3, 5 };
13866  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13867  if (!VDecl->isInvalidDecl() && (DclT != SavT))
13868  VDecl->setType(DclT);
13869 
13870  if (!VDecl->isInvalidDecl()) {
13871  checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13872 
13873  if (VDecl->hasAttr<BlocksAttr>())
13874  checkRetainCycles(VDecl, Init);
13875 
13876  // It is safe to assign a weak reference into a strong variable.
13877  // Although this code can still have problems:
13878  // id x = self.weakProp;
13879  // id y = self.weakProp;
13880  // we do not warn to warn spuriously when 'x' and 'y' are on separate
13881  // paths through the function. This should be revisited if
13882  // -Wrepeated-use-of-weak is made flow-sensitive.
13883  if (FunctionScopeInfo *FSI = getCurFunction())
13884  if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13885  VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13886  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13887  Init->getBeginLoc()))
13888  FSI->markSafeWeakUse(Init);
13889  }
13890 
13891  // The initialization is usually a full-expression.
13892  //
13893  // FIXME: If this is a braced initialization of an aggregate, it is not
13894  // an expression, and each individual field initializer is a separate
13895  // full-expression. For instance, in:
13896  //
13897  // struct Temp { ~Temp(); };
13898  // struct S { S(Temp); };
13899  // struct T { S a, b; } t = { Temp(), Temp() }
13900  //
13901  // we should destroy the first Temp before constructing the second.
13902  ExprResult Result =
13903  ActOnFinishFullExpr(Init, VDecl->getLocation(),
13904  /*DiscardedValue*/ false, VDecl->isConstexpr());
13905  if (Result.isInvalid()) {
13906  VDecl->setInvalidDecl();
13907  return;
13908  }
13909  Init = Result.get();
13910 
13911  // Attach the initializer to the decl.
13912  VDecl->setInit(Init);
13913 
13914  if (VDecl->isLocalVarDecl()) {
13915  // Don't check the initializer if the declaration is malformed.
13916  if (VDecl->isInvalidDecl()) {
13917  // do nothing
13918 
13919  // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13920  // This is true even in C++ for OpenCL.
13921  } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13922  CheckForConstantInitializer(Init);
13923 
13924  // Otherwise, C++ does not restrict the initializer.
13925  } else if (getLangOpts().CPlusPlus) {
13926  // do nothing
13927 
13928  // C99 6.7.8p4: All the expressions in an initializer for an object that has
13929  // static storage duration shall be constant expressions or string literals.
13930  } else if (VDecl->getStorageClass() == SC_Static) {
13931  CheckForConstantInitializer(Init);
13932 
13933  // C89 is stricter than C99 for aggregate initializers.
13934  // C89 6.5.7p3: All the expressions [...] in an initializer list
13935  // for an object that has aggregate or union type shall be
13936  // constant expressions.
13937  } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13938  isa<InitListExpr>(Init)) {
13939  CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13940  }
13941 
13942  if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13943  if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13944  if (VDecl->hasLocalStorage())
13945  BE->getBlockDecl()->setCanAvoidCopyToHeap();
13946  } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13947  VDecl->getLexicalDeclContext()->isRecord()) {
13948  // This is an in-class initialization for a static data member, e.g.,
13949  //
13950  // struct S {
13951  // static const int value = 17;
13952  // };
13953 
13954  // C++ [class.mem]p4:
13955  // A member-declarator can contain a constant-initializer only
13956  // if it declares a static member (9.4) of const integral or
13957  // const enumeration type, see 9.4.2.
13958  //
13959  // C++11 [class.static.data]p3:
13960  // If a non-volatile non-inline const static data member is of integral
13961  // or enumeration type, its declaration in the class definition can
13962  // specify a brace-or-equal-initializer in which every initializer-clause
13963  // that is an assignment-expression is a constant expression. A static
13964  // data member of literal type can be declared in the class definition
13965  // with the constexpr specifier; if so, its declaration shall specify a
13966  // brace-or-equal-initializer in which every initializer-clause that is
13967  // an assignment-expression is a constant expression.
13968 
13969  // Do nothing on dependent types.
13970  if (DclT->isDependentType()) {
13971 
13972  // Allow any 'static constexpr' members, whether or not they are of literal
13973  // type. We separately check that every constexpr variable is of literal
13974  // type.
13975  } else if (VDecl->isConstexpr()) {
13976 
13977  // Require constness.
13978  } else if (!DclT.isConstQualified()) {
13979  Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13980  << Init->getSourceRange();
13981  VDecl->setInvalidDecl();
13982 
13983  // We allow integer constant expressions in all cases.
13984  } else if (DclT->isIntegralOrEnumerationType()) {
13985  // Check whether the expression is a constant expression.
13986  SourceLocation Loc;
13987  if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13988  // In C++11, a non-constexpr const static data member with an
13989  // in-class initializer cannot be volatile.
13990  Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13991  else if (Init->isValueDependent())
13992  ; // Nothing to check.
13993  else if (Init->isIntegerConstantExpr(Context, &Loc))
13994  ; // Ok, it's an ICE!
13995  else if (Init->getType()->isScopedEnumeralType() &&
13996  Init->isCXX11ConstantExpr(Context))
13997  ; // Ok, it is a scoped-enum constant expression.
13998  else if (Init->isEvaluatable(Context)) {
13999  // If we can constant fold the initializer through heroics, accept it,
14000  // but report this as a use of an extension for -pedantic.
14001  Diag(Loc, diag::ext_in_class_initializer_non_constant)
14002  << Init->getSourceRange();
14003  } else {
14004  // Otherwise, this is some crazy unknown case. Report the issue at the
14005  // location provided by the isIntegerConstantExpr failed check.
14006  Diag(Loc, diag::err_in_class_initializer_non_constant)
14007  << Init->getSourceRange();
14008  VDecl->setInvalidDecl();
14009  }
14010 
14011  // We allow foldable floating-point constants as an extension.
14012  } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14013  // In C++98, this is a GNU extension. In C++11, it is not, but we support
14014  // it anyway and provide a fixit to add the 'constexpr'.
14015  if (getLangOpts().CPlusPlus11) {
14016  Diag(VDecl->getLocation(),
14017  diag::ext_in_class_initializer_float_type_cxx11)
14018  << DclT << Init->getSourceRange();
14019  Diag(VDecl->getBeginLoc(),
14020  diag::note_in_class_initializer_float_type_cxx11)
14021  << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14022  } else {
14023  Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14024  << DclT << Init->getSourceRange();
14025 
14026  if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14027  Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14028  << Init->getSourceRange();
14029  VDecl->setInvalidDecl();
14030  }
14031  }
14032 
14033  // Suggest adding 'constexpr' in C++11 for literal types.
14034  } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14035  Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14036  << DclT << Init->getSourceRange()
14037  << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14038  VDecl->setConstexpr(true);
14039 
14040  } else {
14041  Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14042  << DclT << Init->getSourceRange();
14043  VDecl->setInvalidDecl();
14044  }
14045  } else if (VDecl->isFileVarDecl()) {
14046  // In C, extern is typically used to avoid tentative definitions when
14047  // declaring variables in headers, but adding an intializer makes it a
14048  // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14049  // In C++, extern is often used to give implictly static const variables
14050  // external linkage, so don't warn in that case. If selectany is present,
14051  // this might be header code intended for C and C++ inclusion, so apply the
14052  // C++ rules.
14053  if (VDecl->getStorageClass() == SC_Extern &&
14054  ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14055  !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14056  !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14058  Diag(VDecl->getLocation(), diag::warn_extern_init);
14059 
14060  // In Microsoft C++ mode, a const variable defined in namespace scope has
14061  // external linkage by default if the variable is declared with
14062  // __declspec(dllexport).
14063  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14064  getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14065  VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14066  VDecl->setStorageClass(SC_Extern);
14067 
14068  // C99 6.7.8p4. All file scoped initializers need to be constant.
14069  // Avoid duplicate diagnostics for constexpr variables.
14070  if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14071  !VDecl->isConstexpr())
14072  CheckForConstantInitializer(Init);
14073  }
14074 
14075  QualType InitType = Init->getType();
14076  if (!InitType.isNull() &&
14079  checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
14080 
14081  // We will represent direct-initialization similarly to copy-initialization:
14082  // int x(1); -as-> int x = 1;
14083  // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14084  //
14085  // Clients that want to distinguish between the two forms, can check for
14086  // direct initializer using VarDecl::getInitStyle().
14087  // A major benefit is that clients that don't particularly care about which
14088  // exactly form was it (like the CodeGen) can handle both cases without
14089  // special case code.
14090 
14091  // C++ 8.5p11:
14092  // The form of initialization (using parentheses or '=') is generally
14093  // insignificant, but does matter when the entity being initialized has a
14094  // class type.
14095  if (CXXDirectInit) {
14096  assert(DirectInit && "Call-style initializer must be direct init.");
14097  VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14098  : VarDecl::CallInit);
14099  } else if (DirectInit) {
14100  // This must be list-initialization. No other way is direct-initialization.
14102  }
14103 
14104  if (LangOpts.OpenMP &&
14105  (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14106  VDecl->isFileVarDecl())
14107  DeclsToCheckForDeferredDiags.insert(VDecl);
14108  CheckCompleteVariableDeclaration(VDecl);
14109 }
14110 
14111 /// ActOnInitializerError - Given that there was an error parsing an
14112 /// initializer for the given declaration, try to at least re-establish
14113 /// invariants such as whether a variable's type is either dependent or
14114 /// complete.
14116  // Our main concern here is re-establishing invariants like "a
14117  // variable's type is either dependent or complete".
14118  if (!D || D->isInvalidDecl()) return;
14119 
14120  VarDecl *VD = dyn_cast<VarDecl>(D);
14121  if (!VD) return;
14122 
14123  // Bindings are not usable if we can't make sense of the initializer.
14124  if (auto *DD = dyn_cast<DecompositionDecl>(D))
14125  for (auto *BD : DD->bindings())
14126  BD->setInvalidDecl();
14127 
14128  // Auto types are meaningless if we can't make sense of the initializer.
14129  if (VD->getType()->isUndeducedType()) {
14130  D->setInvalidDecl();
14131  return;
14132  }
14133 
14134  QualType Ty = VD->getType();
14135  if (Ty->isDependentType()) return;
14136 
14137  // Require a complete type.
14138  if (RequireCompleteType(VD->getLocation(),
14139  Context.getBaseElementType(Ty),
14140  diag::err_typecheck_decl_incomplete_type)) {
14141  VD->setInvalidDecl();
14142  return;
14143  }
14144 
14145  // Require a non-abstract type.
14146  if (RequireNonAbstractType(VD->getLocation(), Ty,
14147  diag::err_abstract_type_in_decl,
14148  AbstractVariableType)) {
14149  VD->setInvalidDecl();
14150  return;
14151  }
14152 
14153  // Don't bother complaining about constructors or destructors,
14154  // though.
14155 }
14156 
14158  // If there is no declaration, there was an error parsing it. Just ignore it.
14159  if (!RealDecl)
14160  return;
14161 
14162  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14163  QualType Type = Var->getType();
14164 
14165  // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14166  if (isa<DecompositionDecl>(RealDecl)) {
14167  Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14168  Var->setInvalidDecl();
14169  return;
14170  }
14171 
14172  if (Type->isUndeducedType() &&
14173  DeduceVariableDeclarationType(Var, false, nullptr))
14174  return;
14175 
14176  // C++11 [class.static.data]p3: A static data member can be declared with
14177  // the constexpr specifier; if so, its declaration shall specify
14178  // a brace-or-equal-initializer.
14179  // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14180  // the definition of a variable [...] or the declaration of a static data
14181  // member.
14182  if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14183  !Var->isThisDeclarationADemotedDefinition()) {
14184  if (Var->isStaticDataMember()) {
14185  // C++1z removes the relevant rule; the in-class declaration is always
14186  // a definition there.
14187  if (!getLangOpts().CPlusPlus17 &&
14188  !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14189  Diag(Var->getLocation(),
14190  diag::err_constexpr_static_mem_var_requires_init)
14191  << Var;
14192  Var->setInvalidDecl();
14193  return;
14194  }
14195  } else {
14196  Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14197  Var->setInvalidDecl();
14198  return;
14199  }
14200  }
14201 
14202  // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14203  // be initialized.
14204  if (!Var->isInvalidDecl() &&
14205  Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14206  Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14207  bool HasConstExprDefaultConstructor = false;
14208  if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14209  for (auto *Ctor : RD->ctors()) {
14210  if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14211  Ctor->getMethodQualifiers().getAddressSpace() ==
14213  HasConstExprDefaultConstructor = true;
14214  }
14215  }
14216  }
14217  if (!HasConstExprDefaultConstructor) {
14218  Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14219  Var->setInvalidDecl();
14220  return;
14221  }
14222  }
14223 
14224  if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14225  if (Var->getStorageClass() == SC_Extern) {
14226  Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14227  << Var;
14228  Var->setInvalidDecl();
14229  return;
14230  }
14231  if (RequireCompleteType(Var->getLocation(), Var->getType(),
14232  diag::err_typecheck_decl_incomplete_type)) {
14233  Var->setInvalidDecl();
14234  return;
14235  }
14236  if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14237  if (!RD->hasTrivialDefaultConstructor()) {
14238  Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14239  Var->setInvalidDecl();
14240  return;
14241  }
14242  }
14243  // The declaration is unitialized, no need for further checks.
14244  return;
14245  }
14246 
14247  VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14248  if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14249  Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14250  checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14251  NTCUC_DefaultInitializedObject, NTCUK_Init);
14252 
14253 
14254  switch (DefKind) {
14255  case VarDecl::Definition:
14256  if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14257  break;
14258 
14259  // We have an out-of-line definition of a static data member
14260  // that has an in-class initializer, so we type-check this like
14261  // a declaration.
14262  //
14263  [[fallthrough]];
14264 
14266  // It's only a declaration.
14267 
14268  // Block scope. C99 6.7p7: If an identifier for an object is
14269  // declared with no linkage (C99 6.2.2p6), the type for the
14270  // object shall be complete.
14271  if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14272  !Var->hasLinkage() && !Var->isInvalidDecl() &&
14273  RequireCompleteType(Var->getLocation(), Type,
14274  diag::err_typecheck_decl_incomplete_type))
14275  Var->setInvalidDecl();
14276 
14277  // Make sure that the type is not abstract.
14278  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14279  RequireNonAbstractType(Var->getLocation(), Type,
14280  diag::err_abstract_type_in_decl,
14281  AbstractVariableType))
14282  Var->setInvalidDecl();
14283  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14284  Var->getStorageClass() == SC_PrivateExtern) {
14285  Diag(Var->getLocation(), diag::warn_private_extern);
14286  Diag(Var->getLocation(), diag::note_private_extern);
14287  }
14288 
14289  if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14290  !Var->isInvalidDecl())
14291  ExternalDeclarations.push_back(Var);
14292 
14293  return;
14294 
14296  // File scope. C99 6.9.2p2: A declaration of an identifier for an
14297  // object that has file scope without an initializer, and without a
14298  // storage-class specifier or with the storage-class specifier "static",
14299  // constitutes a tentative definition. Note: A tentative definition with
14300  // external linkage is valid (C99 6.2.2p5).
14301  if (!Var->isInvalidDecl()) {
14302  if (const IncompleteArrayType *ArrayT
14303  = Context.getAsIncompleteArrayType(Type)) {
14304  if (RequireCompleteSizedType(
14305  Var->getLocation(), ArrayT->getElementType(),
14306  diag::err_array_incomplete_or_sizeless_type))
14307  Var->setInvalidDecl();
14308  } else if (Var->getStorageClass() == SC_Static) {
14309  // C99 6.9.2p3: If the declaration of an identifier for an object is
14310  // a tentative definition and has internal linkage (C99 6.2.2p3), the
14311  // declared type shall not be an incomplete type.
14312  // NOTE: code such as the following
14313  // static struct s;
14314  // struct s { int a; };
14315  // is accepted by gcc. Hence here we issue a warning instead of
14316  // an error and we do not invalidate the static declaration.
14317  // NOTE: to avoid multiple warnings, only check the first declaration.
14318  if (Var->isFirstDecl())
14319  RequireCompleteType(Var->getLocation(), Type,
14320  diag::ext_typecheck_decl_incomplete_type);
14321  }
14322  }
14323 
14324  // Record the tentative definition; we're done.
14325  if (!Var->isInvalidDecl())
14326  TentativeDefinitions.push_back(Var);
14327  return;
14328  }
14329 
14330  // Provide a specific diagnostic for uninitialized variable
14331  // definitions with incomplete array type.
14332  if (Type->isIncompleteArrayType()) {
14333  if (Var->isConstexpr())
14334  Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14335  << Var;
14336  else
14337  Diag(Var->getLocation(),
14338  diag::err_typecheck_incomplete_array_needs_initializer);
14339  Var->setInvalidDecl();
14340  return;
14341  }
14342 
14343  // Provide a specific diagnostic for uninitialized variable
14344  // definitions with reference type.
14345  if (Type->isReferenceType()) {
14346  Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14347  << Var << SourceRange(Var->getLocation(), Var->getLocation());
14348  return;
14349  }
14350 
14351  // Do not attempt to type-check the default initializer for a
14352  // variable with dependent type.
14353  if (Type->isDependentType())
14354  return;
14355 
14356  if (Var->isInvalidDecl())
14357  return;
14358 
14359  if (!Var->hasAttr<AliasAttr>()) {
14360  if (RequireCompleteType(Var->getLocation(),
14361  Context.getBaseElementType(Type),
14362  diag::err_typecheck_decl_incomplete_type)) {
14363  Var->setInvalidDecl();
14364  return;
14365  }
14366  } else {
14367  return;
14368  }
14369 
14370  // The variable can not have an abstract class type.
14371  if (RequireNonAbstractType(Var->getLocation(), Type,
14372  diag::err_abstract_type_in_decl,
14373  AbstractVariableType)) {
14374  Var->setInvalidDecl();
14375  return;
14376  }
14377 
14378  // Check for jumps past the implicit initializer. C++0x
14379  // clarifies that this applies to a "variable with automatic
14380  // storage duration", not a "local variable".
14381  // C++11 [stmt.dcl]p3
14382  // A program that jumps from a point where a variable with automatic
14383  // storage duration is not in scope to a point where it is in scope is
14384  // ill-formed unless the variable has scalar type, class type with a
14385  // trivial default constructor and a trivial destructor, a cv-qualified
14386  // version of one of these types, or an array of one of the preceding
14387  // types and is declared without an initializer.
14388  if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14389  if (const RecordType *Record
14390  = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14391  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14392  // Mark the function (if we're in one) for further checking even if the
14393  // looser rules of C++11 do not require such checks, so that we can
14394  // diagnose incompatibilities with C++98.
14395  if (!CXXRecord->isPOD())
14396  setFunctionHasBranchProtectedScope();
14397  }
14398  }
14399  // In OpenCL, we can't initialize objects in the __local address space,
14400  // even implicitly, so don't synthesize an implicit initializer.
14401  if (getLangOpts().OpenCL &&
14402  Var->getType().getAddressSpace() == LangAS::opencl_local)
14403  return;
14404  // In SYCL explicit SIMD extension "private global" variables can't be
14405  // initialized even implicitly, so don't synthesize an implicit initializer.
14406  if (SYCL().isSYCLEsimdPrivateGlobal(Var))
14407  return;
14408 
14409  // C++03 [dcl.init]p9:
14410  // If no initializer is specified for an object, and the
14411  // object is of (possibly cv-qualified) non-POD class type (or
14412  // array thereof), the object shall be default-initialized; if
14413  // the object is of const-qualified type, the underlying class
14414  // type shall have a user-declared default
14415  // constructor. Otherwise, if no initializer is specified for
14416  // a non- static object, the object and its subobjects, if
14417  // any, have an indeterminate initial value); if the object
14418  // or any of its subobjects are of const-qualified type, the
14419  // program is ill-formed.
14420  // C++0x [dcl.init]p11:
14421  // If no initializer is specified for an object, the object is
14422  // default-initialized; [...].
14425  = InitializationKind::CreateDefault(Var->getLocation());
14426 
14427  InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14428  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14429 
14430  if (Init.get()) {
14431  Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14432  // This is important for template substitution.
14433  Var->setInitStyle(VarDecl::CallInit);
14434  } else if (Init.isInvalid()) {
14435  // If default-init fails, attach a recovery-expr initializer to track
14436  // that initialization was attempted and failed.
14437  auto RecoveryExpr =
14438  CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14439  if (RecoveryExpr.get())
14440  Var->setInit(RecoveryExpr.get());
14441  }
14442 
14443  CheckCompleteVariableDeclaration(Var);
14444  }
14445 }
14446 
14448  // If there is no declaration, there was an error parsing it. Ignore it.
14449  if (!D)
14450  return;
14451 
14452  VarDecl *VD = dyn_cast<VarDecl>(D);
14453  if (!VD) {
14454  Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14455  D->setInvalidDecl();
14456  return;
14457  }
14458 
14459  VD->setCXXForRangeDecl(true);
14460 
14461  // for-range-declaration cannot be given a storage class specifier.
14462  int Error = -1;
14463  switch (VD->getStorageClass()) {
14464  case SC_None:
14465  break;
14466  case SC_Extern:
14467  Error = 0;
14468  break;
14469  case SC_Static:
14470  Error = 1;
14471  break;
14472  case SC_PrivateExtern:
14473  Error = 2;
14474  break;
14475  case SC_Auto:
14476  Error = 3;
14477  break;
14478  case SC_Register:
14479  Error = 4;
14480  break;
14481  }
14482 
14483  // for-range-declaration cannot be given a storage class specifier con't.
14484  switch (VD->getTSCSpec()) {
14485  case TSCS_thread_local:
14486  Error = 6;
14487  break;
14488  case TSCS___thread:
14489  case TSCS__Thread_local:
14490  case TSCS_unspecified:
14491  break;
14492  }
14493 
14494  if (Error != -1) {
14495  Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14496  << VD << Error;
14497  D->setInvalidDecl();
14498  }
14499 }
14500 
14502  IdentifierInfo *Ident,
14503  ParsedAttributes &Attrs) {
14504  // C++1y [stmt.iter]p1:
14505  // A range-based for statement of the form
14506  // for ( for-range-identifier : for-range-initializer ) statement
14507  // is equivalent to
14508  // for ( auto&& for-range-identifier : for-range-initializer ) statement
14509  DeclSpec DS(Attrs.getPool().getFactory());
14510 
14511  const char *PrevSpec;
14512  unsigned DiagID;
14513  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14514  getPrintingPolicy());
14515 
14517  D.SetIdentifier(Ident, IdentLoc);
14518  D.takeAttributes(Attrs);
14519 
14520  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14521  IdentLoc);
14522  Decl *Var = ActOnDeclarator(S, D);
14523  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14524  FinalizeDeclaration(Var);
14525  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14526  Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14527  : IdentLoc);
14528 }
14529 
14531  if (var->isInvalidDecl()) return;
14532 
14533  CUDA().MaybeAddConstantAttr(var);
14534 
14535  if (getLangOpts().OpenCL) {
14536  // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14537  // initialiser
14538  if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14539  !var->hasInit()) {
14540  Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14541  << 1 /*Init*/;
14542  var->setInvalidDecl();
14543  return;
14544  }
14545  }
14546 
14547  if (getLangOpts().SYCLIsDevice)
14548  SYCL().checkSYCLDeviceVarDecl(var);
14549 
14550  // In Objective-C, don't allow jumps past the implicit initialization of a
14551  // local retaining variable.
14552  if (getLangOpts().ObjC &&
14553  var->hasLocalStorage()) {
14554  switch (var->getType().getObjCLifetime()) {
14555  case Qualifiers::OCL_None:
14558  break;
14559 
14560  case Qualifiers::OCL_Weak:
14562  setFunctionHasBranchProtectedScope();
14563  break;
14564  }
14565  }
14566 
14567  if (var->hasLocalStorage() &&
14568  var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14569  setFunctionHasBranchProtectedScope();
14570 
14571  // Warn about externally-visible variables being defined without a
14572  // prior declaration. We only want to do this for global
14573  // declarations, but we also specifically need to avoid doing it for
14574  // class members because the linkage of an anonymous class can
14575  // change if it's later given a typedef name.
14576  if (var->isThisDeclarationADefinition() &&
14577  var->getDeclContext()->getRedeclContext()->isFileContext() &&
14578  var->isExternallyVisible() && var->hasLinkage() &&
14579  !var->isInline() && !var->getDescribedVarTemplate() &&
14580  var->getStorageClass() != SC_Register &&
14581  !isa<VarTemplatePartialSpecializationDecl>(var) &&
14582  !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14583  !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14584  var->getLocation())) {
14585  // Find a previous declaration that's not a definition.
14586  VarDecl *prev = var->getPreviousDecl();
14587  while (prev && prev->isThisDeclarationADefinition())
14588  prev = prev->getPreviousDecl();
14589 
14590  if (!prev) {
14591  Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14592  Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14593  << /* variable */ 0;
14594  }
14595  }
14596 
14597  // Cache the result of checking for constant initialization.
14598  std::optional<bool> CacheHasConstInit;
14599  const Expr *CacheCulprit = nullptr;
14600  auto checkConstInit = [&]() mutable {
14601  if (!CacheHasConstInit)
14602  CacheHasConstInit = var->getInit()->isConstantInitializer(
14603  Context, var->getType()->isReferenceType(), &CacheCulprit);
14604  return *CacheHasConstInit;
14605  };
14606 
14607  if (var->getTLSKind() == VarDecl::TLS_Static) {
14608  if (var->getType().isDestructedType()) {
14609  // GNU C++98 edits for __thread, [basic.start.term]p3:
14610  // The type of an object with thread storage duration shall not
14611  // have a non-trivial destructor.
14612  Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14613  if (getLangOpts().CPlusPlus11)
14614  Diag(var->getLocation(), diag::note_use_thread_local);
14615  } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14616  if (!checkConstInit()) {
14617  // GNU C++98 edits for __thread, [basic.start.init]p4:
14618  // An object of thread storage duration shall not require dynamic
14619  // initialization.
14620  // FIXME: Need strict checking here.
14621  Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14622  << CacheCulprit->getSourceRange();
14623  if (getLangOpts().CPlusPlus11)
14624  Diag(var->getLocation(), diag::note_use_thread_local);
14625  }
14626  }
14627  }
14628 
14629 
14630  if (!var->getType()->isStructureType() && var->hasInit() &&
14631  isa<InitListExpr>(var->getInit())) {
14632  const auto *ILE = cast<InitListExpr>(var->getInit());
14633  unsigned NumInits = ILE->getNumInits();
14634  if (NumInits > 2)
14635  for (unsigned I = 0; I < NumInits; ++I) {
14636  const auto *Init = ILE->getInit(I);
14637  if (!Init)
14638  break;
14639  const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14640  if (!SL)
14641  break;
14642 
14643  unsigned NumConcat = SL->getNumConcatenated();
14644  // Diagnose missing comma in string array initialization.
14645  // Do not warn when all the elements in the initializer are concatenated
14646  // together. Do not warn for macros too.
14647  if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14648  bool OnlyOneMissingComma = true;
14649  for (unsigned J = I + 1; J < NumInits; ++J) {
14650  const auto *Init = ILE->getInit(J);
14651  if (!Init)
14652  break;
14653  const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14654  if (!SLJ || SLJ->getNumConcatenated() > 1) {
14655  OnlyOneMissingComma = false;
14656  break;
14657  }
14658  }
14659 
14660  if (OnlyOneMissingComma) {
14662  for (unsigned i = 0; i < NumConcat - 1; ++i)
14663  Hints.push_back(FixItHint::CreateInsertion(
14664  PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14665 
14666  Diag(SL->getStrTokenLoc(1),
14667  diag::warn_concatenated_literal_array_init)
14668  << Hints;
14669  Diag(SL->getBeginLoc(),
14670  diag::note_concatenated_string_literal_silence);
14671  }
14672  // In any case, stop now.
14673  break;
14674  }
14675  }
14676  }
14677 
14678 
14679  QualType type = var->getType();
14680 
14681  if (var->hasAttr<BlocksAttr>())
14682  getCurFunction()->addByrefBlockVar(var);
14683 
14684  Expr *Init = var->getInit();
14685  bool GlobalStorage = var->hasGlobalStorage();
14686  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14687  QualType baseType = Context.getBaseElementType(type);
14688  bool HasConstInit = true;
14689 
14690  if (getLangOpts().C23 && var->isConstexpr() && !Init)
14691  Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14692  << var;
14693 
14694  // Check whether the initializer is sufficiently constant.
14695  if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14696  !type->isDependentType() && Init && !Init->isValueDependent() &&
14697  (GlobalStorage || var->isConstexpr() ||
14698  var->mightBeUsableInConstantExpressions(Context))) {
14699  // If this variable might have a constant initializer or might be usable in
14700  // constant expressions, check whether or not it actually is now. We can't
14701  // do this lazily, because the result might depend on things that change
14702  // later, such as which constexpr functions happen to be defined.
14704  if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14705  // Prior to C++11, in contexts where a constant initializer is required,
14706  // the set of valid constant initializers is described by syntactic rules
14707  // in [expr.const]p2-6.
14708  // FIXME: Stricter checking for these rules would be useful for constinit /
14709  // -Wglobal-constructors.
14710  HasConstInit = checkConstInit();
14711 
14712  // Compute and cache the constant value, and remember that we have a
14713  // constant initializer.
14714  if (HasConstInit) {
14715  (void)var->checkForConstantInitialization(Notes);
14716  Notes.clear();
14717  } else if (CacheCulprit) {
14718  Notes.emplace_back(CacheCulprit->getExprLoc(),
14719  PDiag(diag::note_invalid_subexpr_in_const_expr));
14720  Notes.back().second << CacheCulprit->getSourceRange();
14721  }
14722  } else {
14723  // Evaluate the initializer to see if it's a constant initializer.
14724  HasConstInit = var->checkForConstantInitialization(Notes);
14725  }
14726 
14727  if (HasConstInit) {
14728  // FIXME: Consider replacing the initializer with a ConstantExpr.
14729  } else if (var->isConstexpr()) {
14730  SourceLocation DiagLoc = var->getLocation();
14731  // If the note doesn't add any useful information other than a source
14732  // location, fold it into the primary diagnostic.
14733  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14734  diag::note_invalid_subexpr_in_const_expr) {
14735  DiagLoc = Notes[0].first;
14736  Notes.clear();
14737  }
14738  Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14739  << var << Init->getSourceRange();
14740  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14741  Diag(Notes[I].first, Notes[I].second);
14742  } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14743  auto *Attr = var->getAttr<ConstInitAttr>();
14744  Diag(var->getLocation(), diag::err_require_constant_init_failed)
14745  << Init->getSourceRange();
14746  Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14747  << Attr->getRange() << Attr->isConstinit();
14748  for (auto &it : Notes)
14749  Diag(it.first, it.second);
14750  } else if (IsGlobal &&
14751  !getDiagnostics().isIgnored(diag::warn_global_constructor,
14752  var->getLocation())) {
14753  // Warn about globals which don't have a constant initializer. Don't
14754  // warn about globals with a non-trivial destructor because we already
14755  // warned about them.
14756  CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14757  if (!(RD && !RD->hasTrivialDestructor())) {
14758  // checkConstInit() here permits trivial default initialization even in
14759  // C++11 onwards, where such an initializer is not a constant initializer
14760  // but nonetheless doesn't require a global constructor.
14761  if (!checkConstInit())
14762  Diag(var->getLocation(), diag::warn_global_constructor)
14763  << Init->getSourceRange();
14764  }
14765  }
14766  }
14767 
14768  // Apply section attributes and pragmas to global variables.
14769  if (GlobalStorage && var->isThisDeclarationADefinition() &&
14770  !inTemplateInstantiation()) {
14771  PragmaStack<StringLiteral *> *Stack = nullptr;
14772  int SectionFlags = ASTContext::PSF_Read;
14773  bool MSVCEnv =
14774  Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14775  std::optional<QualType::NonConstantStorageReason> Reason;
14776  if (HasConstInit &&
14777  !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14778  Stack = &ConstSegStack;
14779  } else {
14780  SectionFlags |= ASTContext::PSF_Write;
14781  Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14782  }
14783  if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14784  if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14785  SectionFlags |= ASTContext::PSF_Implicit;
14786  UnifySection(SA->getName(), SectionFlags, var);
14787  } else if (Stack->CurrentValue) {
14788  if (Stack != &ConstSegStack && MSVCEnv &&
14789  ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14790  var->getType().isConstQualified()) {
14791  assert((!Reason || Reason != QualType::NonConstantStorageReason::
14792  NonConstNonReferenceType) &&
14793  "This case should've already been handled elsewhere");
14794  Diag(var->getLocation(), diag::warn_section_msvc_compat)
14795  << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14797  : *Reason);
14798  }
14799  SectionFlags |= ASTContext::PSF_Implicit;
14800  auto SectionName = Stack->CurrentValue->getString();
14801  var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14802  Stack->CurrentPragmaLocation,
14803  SectionAttr::Declspec_allocate));
14804  if (UnifySection(SectionName, SectionFlags, var))
14805  var->dropAttr<SectionAttr>();
14806  }
14807 
14808  // Apply the init_seg attribute if this has an initializer. If the
14809  // initializer turns out to not be dynamic, we'll end up ignoring this
14810  // attribute.
14811  if (CurInitSeg && var->getInit())
14812  var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14813  CurInitSegLoc));
14814  }
14815 
14816  // All the following checks are C++ only.
14817  if (!getLangOpts().CPlusPlus) {
14818  // If this variable must be emitted, add it as an initializer for the
14819  // current module.
14820  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14821  Context.addModuleInitializer(ModuleScopes.back().Module, var);
14822  return;
14823  }
14824 
14825  // Require the destructor.
14826  if (!type->isDependentType())
14827  if (const RecordType *recordType = baseType->getAs<RecordType>())
14828  FinalizeVarWithDestructor(var, recordType);
14829 
14830  // If this variable must be emitted, add it as an initializer for the current
14831  // module.
14832  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14833  Context.addModuleInitializer(ModuleScopes.back().Module, var);
14834 
14835  // Build the bindings if this is a structured binding declaration.
14836  if (auto *DD = dyn_cast<DecompositionDecl>(var))
14837  CheckCompleteDecompositionDeclaration(DD);
14838 }
14839 
14840 /// Check if VD needs to be dllexport/dllimport due to being in a
14841 /// dllexport/import function.
14843  assert(VD->isStaticLocal());
14844 
14845  auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14846 
14847  // Find outermost function when VD is in lambda function.
14848  while (FD && !getDLLAttr(FD) &&
14849  !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14850  !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14851  FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14852  }
14853 
14854  if (!FD)
14855  return;
14856 
14857  // Static locals inherit dll attributes from their function.
14858  if (Attr *A = getDLLAttr(FD)) {
14859  auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14860  NewAttr->setInherited(true);
14861  VD->addAttr(NewAttr);
14862  } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14863  auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14864  NewAttr->setInherited(true);
14865  VD->addAttr(NewAttr);
14866 
14867  // Export this function to enforce exporting this static variable even
14868  // if it is not used in this compilation unit.
14869  if (!FD->hasAttr<DLLExportAttr>())
14870  FD->addAttr(NewAttr);
14871 
14872  } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14873  auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14874  NewAttr->setInherited(true);
14875  VD->addAttr(NewAttr);
14876  }
14877 }
14878 
14880  assert(VD->getTLSKind());
14881 
14882  // Perform TLS alignment check here after attributes attached to the variable
14883  // which may affect the alignment have been processed. Only perform the check
14884  // if the target has a maximum TLS alignment (zero means no constraints).
14885  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14886  // Protect the check so that it's not performed on dependent types and
14887  // dependent alignments (we can't determine the alignment in that case).
14888  if (!VD->hasDependentAlignment()) {
14889  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14890  if (Context.getDeclAlign(VD) > MaxAlignChars) {
14891  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14892  << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14893  << (unsigned)MaxAlignChars.getQuantity();
14894  }
14895  }
14896  }
14897 }
14898 
14899 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14900 /// any semantic actions necessary after any initializer has been attached.
14902  // Note that we are no longer parsing the initializer for this declaration.
14903  ParsingInitForAutoVars.erase(ThisDecl);
14904 
14905  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14906  if (!VD)
14907  return;
14908 
14909  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14910  if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14911  !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14912  if (PragmaClangBSSSection.Valid)
14913  VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14914  Context, PragmaClangBSSSection.SectionName,
14915  PragmaClangBSSSection.PragmaLocation));
14916  if (PragmaClangDataSection.Valid)
14917  VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14918  Context, PragmaClangDataSection.SectionName,
14919  PragmaClangDataSection.PragmaLocation));
14920  if (PragmaClangRodataSection.Valid)
14921  VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14922  Context, PragmaClangRodataSection.SectionName,
14923  PragmaClangRodataSection.PragmaLocation));
14924  if (PragmaClangRelroSection.Valid)
14925  VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14926  Context, PragmaClangRelroSection.SectionName,
14927  PragmaClangRelroSection.PragmaLocation));
14928  }
14929 
14930  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14931  for (auto *BD : DD->bindings()) {
14932  FinalizeDeclaration(BD);
14933  }
14934  }
14935 
14936  checkAttributesAfterMerging(*this, *VD);
14937 
14938  if (VD->isStaticLocal())
14939  CheckStaticLocalForDllExport(VD);
14940 
14941  if (VD->getTLSKind())
14942  CheckThreadLocalForLargeAlignment(VD);
14943 
14944  // Perform check for initializers of device-side global variables.
14945  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14946  // 7.5). We must also apply the same checks to all __shared__
14947  // variables whether they are local or not. CUDA also allows
14948  // constant initializers for __constant__ and __device__ variables.
14949  if (getLangOpts().CUDA)
14950  CUDA().checkAllowedInitializer(VD);
14951 
14952  // Grab the dllimport or dllexport attribute off of the VarDecl.
14953  const InheritableAttr *DLLAttr = getDLLAttr(VD);
14954 
14955  // Imported static data members cannot be defined out-of-line.
14956  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14957  if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14959  // We allow definitions of dllimport class template static data members
14960  // with a warning.
14961  CXXRecordDecl *Context =
14962  cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14963  bool IsClassTemplateMember =
14964  isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14965  Context->getDescribedClassTemplate();
14966 
14967  Diag(VD->getLocation(),
14968  IsClassTemplateMember
14969  ? diag::warn_attribute_dllimport_static_field_definition
14970  : diag::err_attribute_dllimport_static_field_definition);
14971  Diag(IA->getLocation(), diag::note_attribute);
14972  if (!IsClassTemplateMember)
14973  VD->setInvalidDecl();
14974  }
14975  }
14976 
14977  // dllimport/dllexport variables cannot be thread local, their TLS index
14978  // isn't exported with the variable.
14979  if (DLLAttr && VD->getTLSKind()) {
14980  auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14981  if (F && getDLLAttr(F)) {
14982  assert(VD->isStaticLocal());
14983  // But if this is a static local in a dlimport/dllexport function, the
14984  // function will never be inlined, which means the var would never be
14985  // imported, so having it marked import/export is safe.
14986  } else {
14987  Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14988  << DLLAttr;
14989  VD->setInvalidDecl();
14990  }
14991  }
14992 
14993  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14994  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14995  Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14996  << Attr;
14997  VD->dropAttr<UsedAttr>();
14998  }
14999  }
15000  if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15001  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15002  Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15003  << Attr;
15004  VD->dropAttr<RetainAttr>();
15005  }
15006  }
15007 
15008  const DeclContext *DC = VD->getDeclContext();
15009  // If there's a #pragma GCC visibility in scope, and this isn't a class
15010  // member, set the visibility of this variable.
15011  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15012  AddPushedVisibilityAttribute(VD);
15013 
15014  // FIXME: Warn on unused var template partial specializations.
15015  if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
15016  MarkUnusedFileScopedDecl(VD);
15017 
15018  // Now we have parsed the initializer and can update the table of magic
15019  // tag values.
15020  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15022  return;
15023 
15024  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15025  const Expr *MagicValueExpr = VD->getInit();
15026  if (!MagicValueExpr) {
15027  continue;
15028  }
15029  std::optional<llvm::APSInt> MagicValueInt;
15030  if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15031  Diag(I->getRange().getBegin(),
15032  diag::err_type_tag_for_datatype_not_ice)
15033  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15034  continue;
15035  }
15036  if (MagicValueInt->getActiveBits() > 64) {
15037  Diag(I->getRange().getBegin(),
15038  diag::err_type_tag_for_datatype_too_large)
15039  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15040  continue;
15041  }
15042  uint64_t MagicValue = MagicValueInt->getZExtValue();
15043  RegisterTypeTagForDatatype(I->getArgumentKind(),
15044  MagicValue,
15045  I->getMatchingCType(),
15046  I->getLayoutCompatible(),
15047  I->getMustBeNull());
15048  }
15049 }
15050 
15051 static bool hasDeducedAuto(DeclaratorDecl *DD) {
15052  auto *VD = dyn_cast<VarDecl>(DD);
15053  return VD && !VD->getType()->hasAutoForTrailingReturnType();
15054 }
15055 
15058  SmallVector<Decl*, 8> Decls;
15059 
15060  if (DS.isTypeSpecOwned())
15061  Decls.push_back(DS.getRepAsDecl());
15062 
15063  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15064  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15065  bool DiagnosedMultipleDecomps = false;
15066  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15067  bool DiagnosedNonDeducedAuto = false;
15068 
15069  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15070  if (Decl *D = Group[i]) {
15071  // Check if the Decl has been declared in '#pragma omp declare target'
15072  // directive and has static storage duration.
15073  if (auto *VD = dyn_cast<VarDecl>(D);
15074  LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15075  VD->hasGlobalStorage())
15076  OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15077  // For declarators, there are some additional syntactic-ish checks we need
15078  // to perform.
15079  if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15080  if (!FirstDeclaratorInGroup)
15081  FirstDeclaratorInGroup = DD;
15082  if (!FirstDecompDeclaratorInGroup)
15083  FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15084  if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15085  !hasDeducedAuto(DD))
15086  FirstNonDeducedAutoInGroup = DD;
15087 
15088  if (FirstDeclaratorInGroup != DD) {
15089  // A decomposition declaration cannot be combined with any other
15090  // declaration in the same group.
15091  if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15092  Diag(FirstDecompDeclaratorInGroup->getLocation(),
15093  diag::err_decomp_decl_not_alone)
15094  << FirstDeclaratorInGroup->getSourceRange()
15095  << DD->getSourceRange();
15096  DiagnosedMultipleDecomps = true;
15097  }
15098 
15099  // A declarator that uses 'auto' in any way other than to declare a
15100  // variable with a deduced type cannot be combined with any other
15101  // declarator in the same group.
15102  if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15103  Diag(FirstNonDeducedAutoInGroup->getLocation(),
15104  diag::err_auto_non_deduced_not_alone)
15105  << FirstNonDeducedAutoInGroup->getType()
15107  << FirstDeclaratorInGroup->getSourceRange()
15108  << DD->getSourceRange();
15109  DiagnosedNonDeducedAuto = true;
15110  }
15111  }
15112  }
15113 
15114  Decls.push_back(D);
15115  }
15116  }
15117 
15119  if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15120  handleTagNumbering(Tag, S);
15121  if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15122  getLangOpts().CPlusPlus)
15123  Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15124  }
15125  }
15126 
15127  return BuildDeclaratorGroup(Decls);
15128 }
15129 
15130 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
15131 /// group, performing any necessary semantic checking.
15134  // C++14 [dcl.spec.auto]p7: (DR1347)
15135  // If the type that replaces the placeholder type is not the same in each
15136  // deduction, the program is ill-formed.
15137  if (Group.size() > 1) {
15138  QualType Deduced;
15139  VarDecl *DeducedDecl = nullptr;
15140  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15141  VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15142  if (!D || D->isInvalidDecl())
15143  break;
15145  if (!DT || DT->getDeducedType().isNull())
15146  continue;
15147  if (Deduced.isNull()) {
15148  Deduced = DT->getDeducedType();
15149  DeducedDecl = D;
15150  } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15151  auto *AT = dyn_cast<AutoType>(DT);
15152  auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15153  diag::err_auto_different_deductions)
15154  << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15155  << DeducedDecl->getDeclName() << DT->getDeducedType()
15156  << D->getDeclName();
15157  if (DeducedDecl->hasInit())
15158  Dia << DeducedDecl->getInit()->getSourceRange();
15159  if (D->getInit())
15160  Dia << D->getInit()->getSourceRange();
15161  D->setInvalidDecl();
15162  break;
15163  }
15164  }
15165  }
15166 
15167  ActOnDocumentableDecls(Group);
15168 
15169  return DeclGroupPtrTy::make(
15170  DeclGroupRef::Create(Context, Group.data(), Group.size()));
15171 }
15172 
15174  ActOnDocumentableDecls(D);
15175 }
15176 
15178  // Don't parse the comment if Doxygen diagnostics are ignored.
15179  if (Group.empty() || !Group[0])
15180  return;
15181 
15182  if (Diags.isIgnored(diag::warn_doc_param_not_found,
15183  Group[0]->getLocation()) &&
15184  Diags.isIgnored(diag::warn_unknown_comment_command_name,
15185  Group[0]->getLocation()))
15186  return;
15187 
15188  if (Group.size() >= 2) {
15189  // This is a decl group. Normally it will contain only declarations
15190  // produced from declarator list. But in case we have any definitions or
15191  // additional declaration references:
15192  // 'typedef struct S {} S;'
15193  // 'typedef struct S *S;'
15194  // 'struct S *pS;'
15195  // FinalizeDeclaratorGroup adds these as separate declarations.
15196  Decl *MaybeTagDecl = Group[0];
15197  if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15198  Group = Group.slice(1);
15199  }
15200  }
15201 
15202  // FIMXE: We assume every Decl in the group is in the same file.
15203  // This is false when preprocessor constructs the group from decls in
15204  // different files (e. g. macros or #include).
15205  Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15206 }
15207 
15208 /// Common checks for a parameter-declaration that should apply to both function
15209 /// parameters and non-type template parameters.
15211  // Check that there are no default arguments inside the type of this
15212  // parameter.
15213  if (getLangOpts().CPlusPlus)
15214  CheckExtraCXXDefaultArguments(D);
15215 
15216  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15217  if (D.getCXXScopeSpec().isSet()) {
15218  Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15219  << D.getCXXScopeSpec().getRange();
15220  }
15221 
15222  // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15223  // simple identifier except [...irrelevant cases...].
15224  switch (D.getName().getKind()) {
15226  break;
15227 
15235  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15236  << GetNameForDeclarator(D).getName();
15237  break;
15238 
15241  // GetNameForDeclarator would not produce a useful name in this case.
15242  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15243  break;
15244  }
15245 }
15246 
15248  SourceLocation ExplicitThisLoc) {
15249  if (!ExplicitThisLoc.isValid())
15250  return;
15251  assert(S.getLangOpts().CPlusPlus &&
15252  "explicit parameter in non-cplusplus mode");
15253  if (!S.getLangOpts().CPlusPlus23)
15254  S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15255  << P->getSourceRange();
15256 
15257  // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15258  // parameter pack.
15259  if (P->isParameterPack()) {
15260  S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15261  << P->getSourceRange();
15262  return;
15263  }
15264  P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15265  if (LambdaScopeInfo *LSI = S.getCurLambda())
15266  LSI->ExplicitObjectParameter = P;
15267 }
15268 
15269 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15270 /// to introduce parameters into function prototype scope.
15272  SourceLocation ExplicitThisLoc) {
15273  const DeclSpec &DS = D.getDeclSpec();
15274 
15275  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15276 
15277  // C++03 [dcl.stc]p2 also permits 'auto'.
15278  StorageClass SC = SC_None;
15280  SC = SC_Register;
15281  // In C++11, the 'register' storage class specifier is deprecated.
15282  // In C++17, it is not allowed, but we tolerate it as an extension.
15283  if (getLangOpts().CPlusPlus11) {
15285  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15286  : diag::warn_deprecated_register)
15288  }
15289  } else if (getLangOpts().CPlusPlus &&
15291  SC = SC_Auto;
15292  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15294  diag::err_invalid_storage_class_in_func_decl);
15296  }
15297 
15298  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15299  Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15300  << DeclSpec::getSpecifierName(TSCS);
15301  if (DS.isInlineSpecified())
15302  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15303  << getLangOpts().CPlusPlus17;
15304  if (DS.hasConstexprSpecifier())
15305  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15306  << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15307 
15308  DiagnoseFunctionSpecifiers(DS);
15309 
15310  CheckFunctionOrTemplateParamDeclarator(S, D);
15311 
15312  TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15313  QualType parmDeclType = TInfo->getType();
15314 
15315  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15316  const IdentifierInfo *II = D.getIdentifier();
15317  if (II) {
15318  LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15320  LookupName(R, S);
15321  if (!R.empty()) {
15322  NamedDecl *PrevDecl = *R.begin();
15323  if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15324  // Maybe we will complain about the shadowed template parameter.
15325  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15326  // Just pretend that we didn't see the previous declaration.
15327  PrevDecl = nullptr;
15328  }
15329  if (PrevDecl && S->isDeclScope(PrevDecl)) {
15330  Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15331  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15332  // Recover by removing the name
15333  II = nullptr;
15334  D.SetIdentifier(nullptr, D.getIdentifierLoc());
15335  D.setInvalidType(true);
15336  }
15337  }
15338  }
15339 
15340  // Temporarily put parameter variables in the translation unit, not
15341  // the enclosing context. This prevents them from accidentally
15342  // looking like class members in C++.
15343  ParmVarDecl *New =
15344  CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15345  D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15346 
15347  if (D.isInvalidType())
15348  New->setInvalidDecl();
15349 
15350  CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15351 
15352  assert(S->isFunctionPrototypeScope());
15353  assert(S->getFunctionPrototypeDepth() >= 1);
15354  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15355  S->getNextFunctionPrototypeIndex());
15356 
15357  // Add the parameter declaration into this scope.
15358  S->AddDecl(New);
15359  if (II)
15360  IdResolver.AddDecl(New);
15361 
15362  ProcessDeclAttributes(S, New, D);
15363 
15365  Diag(New->getLocation(), diag::err_module_private_local)
15366  << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15368 
15369  if (New->hasAttr<BlocksAttr>()) {
15370  Diag(New->getLocation(), diag::err_block_on_nonlocal);
15371  }
15372 
15373  if (getLangOpts().OpenCL)
15374  deduceOpenCLAddressSpace(New);
15375 
15376  return New;
15377 }
15378 
15379 /// Synthesizes a variable for a parameter arising from a
15380 /// typedef.
15382  SourceLocation Loc,
15383  QualType T) {
15384  /* FIXME: setting StartLoc == Loc.
15385  Would it be worth to modify callers so as to provide proper source
15386  location for the unnamed parameters, embedding the parameter's type? */
15387  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15388  T, Context.getTrivialTypeSourceInfo(T, Loc),
15389  SC_None, nullptr);
15390  Param->setImplicit();
15391  return Param;
15392 }
15393 
15395  // Don't diagnose unused-parameter errors in template instantiations; we
15396  // will already have done so in the template itself.
15397  if (inTemplateInstantiation())
15398  return;
15399 
15400  for (const ParmVarDecl *Parameter : Parameters) {
15401  if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15402  !Parameter->hasAttr<UnusedAttr>() &&
15403  !Parameter->getIdentifier()->isPlaceholder()) {
15404  Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15405  << Parameter->getDeclName();
15406  }
15407  }
15408 }
15409 
15411  ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15412  if (LangOpts.NumLargeByValueCopy == 0) // No check.
15413  return;
15414 
15415  // Warn if the return value is pass-by-value and larger than the specified
15416  // threshold.
15417  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15418  unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15419  if (Size > LangOpts.NumLargeByValueCopy)
15420  Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15421  }
15422 
15423  // Warn if any parameter is pass-by-value and larger than the specified
15424  // threshold.
15425  for (const ParmVarDecl *Parameter : Parameters) {
15426  QualType T = Parameter->getType();
15427  if (T->isDependentType() || !T.isPODType(Context))
15428  continue;
15429  unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15430  if (Size > LangOpts.NumLargeByValueCopy)
15431  Diag(Parameter->getLocation(), diag::warn_parameter_size)
15432  << Parameter << Size;
15433  }
15434 }
15435 
15437  SourceLocation NameLoc,
15438  TypeSourceInfo *TSInfo) {
15439  // In ARC, infer a lifetime qualifier for appropriate parameter types.
15440  if (!getLangOpts().ObjCAutoRefCount ||
15441  T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType())
15442  return T;
15443 
15444  Qualifiers::ObjCLifetime Lifetime;
15445 
15446  // Special cases for arrays:
15447  // - if it's const, use __unsafe_unretained
15448  // - otherwise, it's an error
15449  if (T->isArrayType()) {
15450  if (!T.isConstQualified()) {
15453  NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15454  else
15455  Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15456  << TSInfo->getTypeLoc().getSourceRange();
15457  }
15458  Lifetime = Qualifiers::OCL_ExplicitNone;
15459  } else {
15460  Lifetime = T->getObjCARCImplicitLifetime();
15461  }
15462  T = Context.getLifetimeQualifiedType(T, Lifetime);
15463 
15464  return T;
15465 }
15466 
15468  SourceLocation NameLoc,
15469  const IdentifierInfo *Name, QualType T,
15470  TypeSourceInfo *TSInfo, StorageClass SC) {
15471  // In ARC, infer a lifetime qualifier for appropriate parameter types.
15472  if (getLangOpts().ObjCAutoRefCount &&
15473  T.getObjCLifetime() == Qualifiers::OCL_None &&
15474  T->isObjCLifetimeType()) {
15475 
15476  Qualifiers::ObjCLifetime lifetime;
15477 
15478  // Special cases for arrays:
15479  // - if it's const, use __unsafe_unretained
15480  // - otherwise, it's an error
15481  if (T->isArrayType()) {
15482  if (!T.isConstQualified()) {
15486  NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15487  else
15488  Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15489  << TSInfo->getTypeLoc().getSourceRange();
15490  }
15491  lifetime = Qualifiers::OCL_ExplicitNone;
15492  } else {
15493  lifetime = T->getObjCARCImplicitLifetime();
15494  }
15495  T = Context.getLifetimeQualifiedType(T, lifetime);
15496  }
15497 
15498  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15499  Context.getAdjustedParameterType(T),
15500  TSInfo, SC, nullptr);
15501 
15502  // Make a note if we created a new pack in the scope of a lambda, so that
15503  // we know that references to that pack must also be expanded within the
15504  // lambda scope.
15505  if (New->isParameterPack())
15506  if (auto *LSI = getEnclosingLambda())
15507  LSI->LocalPacks.push_back(New);
15508 
15511  checkNonTrivialCUnion(New->getType(), New->getLocation(),
15512  NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15513 
15514  // Parameter declarators cannot be interface types. All ObjC objects are
15515  // passed by reference.
15516  if (T->isObjCObjectType()) {
15517  SourceLocation TypeEndLoc =
15518  getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15519  Diag(NameLoc,
15520  diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15521  << FixItHint::CreateInsertion(TypeEndLoc, "*");
15522  T = Context.getObjCObjectPointerType(T);
15523  New->setType(T);
15524  }
15525 
15526  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15527  // duration shall not be qualified by an address-space qualifier."
15528  // Since all parameters have automatic store duration, they can not have
15529  // an address space.
15530  if (T.getAddressSpace() != LangAS::Default &&
15531  // OpenCL allows function arguments declared to be an array of a type
15532  // to be qualified with an address space.
15533  !(getLangOpts().OpenCL &&
15534  (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15535  // WebAssembly allows reference types as parameters. Funcref in particular
15536  // lives in a different address space.
15537  !(T->isFunctionPointerType() &&
15538  T.getAddressSpace() == LangAS::wasm_funcref)) {
15539  Diag(NameLoc, diag::err_arg_with_address_space);
15540  New->setInvalidDecl();
15541  }
15542 
15543  // PPC MMA non-pointer types are not allowed as function argument types.
15544  if (Context.getTargetInfo().getTriple().isPPC64() &&
15545  CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15546  New->setInvalidDecl();
15547  }
15548 
15549  return New;
15550 }
15551 
15553  SourceLocation LocAfterDecls) {
15555 
15556  // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15557  // in the declaration list shall have at least one declarator, those
15558  // declarators shall only declare identifiers from the identifier list, and
15559  // every identifier in the identifier list shall be declared.
15560  //
15561  // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15562  // identifiers it names shall be declared in the declaration list."
15563  //
15564  // This is why we only diagnose in C99 and later. Note, the other conditions
15565  // listed are checked elsewhere.
15566  if (!FTI.hasPrototype) {
15567  for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15568  --i;
15569  if (FTI.Params[i].Param == nullptr) {
15570  if (getLangOpts().C99) {
15571  SmallString<256> Code;
15572  llvm::raw_svector_ostream(Code)
15573  << " int " << FTI.Params[i].Ident->getName() << ";\n";
15574  Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15575  << FTI.Params[i].Ident
15576  << FixItHint::CreateInsertion(LocAfterDecls, Code);
15577  }
15578 
15579  // Implicitly declare the argument as type 'int' for lack of a better
15580  // type.
15581  AttributeFactory attrs;
15582  DeclSpec DS(attrs);
15583  const char* PrevSpec; // unused
15584  unsigned DiagID; // unused
15585  DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15586  DiagID, Context.getPrintingPolicy());
15587  // Use the identifier location for the type source range.
15588  DS.SetRangeStart(FTI.Params[i].IdentLoc);
15589  DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15592  ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15593  FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15594  }
15595  }
15596  }
15597 }
15598 
15599 Decl *
15601  MultiTemplateParamsArg TemplateParameterLists,
15602  SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15603  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15604  assert(D.isFunctionDeclarator() && "Not a function declarator!");
15605  Scope *ParentScope = FnBodyScope->getParent();
15606 
15607  // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15608  // we define a non-templated function definition, we will create a declaration
15609  // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15610  // The base function declaration will have the equivalent of an `omp declare
15611  // variant` annotation which specifies the mangled definition as a
15612  // specialization function under the OpenMP context defined as part of the
15613  // `omp begin declare variant`.
15615  if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15616  OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15617  ParentScope, D, TemplateParameterLists, Bases);
15618 
15620  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15621  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15622 
15623  if (!Bases.empty())
15624  OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
15625  Bases);
15626 
15627  return Dcl;
15628 }
15629 
15631  Consumer.HandleInlineFunctionDefinition(D);
15632 }
15633 
15634 static bool FindPossiblePrototype(const FunctionDecl *FD,
15635  const FunctionDecl *&PossiblePrototype) {
15636  for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15637  Prev = Prev->getPreviousDecl()) {
15638  // Ignore any declarations that occur in function or method
15639  // scope, because they aren't visible from the header.
15640  if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15641  continue;
15642 
15643  PossiblePrototype = Prev;
15644  return Prev->getType()->isFunctionProtoType();
15645  }
15646  return false;
15647 }
15648 
15649 static bool
15651  const FunctionDecl *&PossiblePrototype) {
15652  // Don't warn about invalid declarations.
15653  if (FD->isInvalidDecl())
15654  return false;
15655 
15656  // Or declarations that aren't global.
15657  if (!FD->isGlobal())
15658  return false;
15659 
15660  // Don't warn about C++ member functions.
15661  if (isa<CXXMethodDecl>(FD))
15662  return false;
15663 
15664  // Don't warn about 'main'.
15665  if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15666  if (IdentifierInfo *II = FD->getIdentifier())
15667  if (II->isStr("main") || II->isStr("efi_main"))
15668  return false;
15669 
15670  // Don't warn about inline functions.
15671  if (FD->isInlined())
15672  return false;
15673 
15674  // Don't warn about function templates.
15675  if (FD->getDescribedFunctionTemplate())
15676  return false;
15677 
15678  // Don't warn about function template specializations.
15680  return false;
15681 
15682  // Don't warn for OpenCL kernels.
15683  if (FD->hasAttr<OpenCLKernelAttr>())
15684  return false;
15685 
15686  // Don't warn on explicitly deleted functions.
15687  if (FD->isDeleted())
15688  return false;
15689 
15690  // Don't warn on implicitly local functions (such as having local-typed
15691  // parameters).
15692  if (!FD->isExternallyVisible())
15693  return false;
15694 
15695  // If we were able to find a potential prototype, don't warn.
15696  if (FindPossiblePrototype(FD, PossiblePrototype))
15697  return false;
15698 
15699  return true;
15700 }
15701 
15702 void
15704  const FunctionDecl *EffectiveDefinition,
15705  SkipBodyInfo *SkipBody) {
15706  const FunctionDecl *Definition = EffectiveDefinition;
15707  if (!Definition &&
15708  !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15709  return;
15710 
15711  if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15712  if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15713  if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15714  // A merged copy of the same function, instantiated as a member of
15715  // the same class, is OK.
15716  if (declaresSameEntity(OrigFD, OrigDef) &&
15717  declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15718  cast<Decl>(FD->getLexicalDeclContext())))
15719  return;
15720  }
15721  }
15722  }
15723 
15724  if (canRedefineFunction(Definition, getLangOpts()))
15725  return;
15726 
15727  // Don't emit an error when this is redefinition of a typo-corrected
15728  // definition.
15729  if (TypoCorrectedFunctionDefinitions.count(Definition))
15730  return;
15731 
15732  // If we don't have a visible definition of the function, and it's inline or
15733  // a template, skip the new definition.
15734  if (SkipBody && !hasVisibleDefinition(Definition) &&
15735  (Definition->getFormalLinkage() == Linkage::Internal ||
15736  Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15737  Definition->getNumTemplateParameterLists())) {
15738  SkipBody->ShouldSkip = true;
15739  SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15740  if (auto *TD = Definition->getDescribedFunctionTemplate())
15741  makeMergedDefinitionVisible(TD);
15742  makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15743  return;
15744  }
15745 
15746  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15747  Definition->getStorageClass() == SC_Extern)
15748  Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15749  << FD << getLangOpts().CPlusPlus;
15750  else
15751  Diag(FD->getLocation(), diag::err_redefinition) << FD;
15752 
15753  Diag(Definition->getLocation(), diag::note_previous_definition);
15754  FD->setInvalidDecl();
15755 }
15756 
15758  CXXRecordDecl *LambdaClass = CallOperator->getParent();
15759 
15760  LambdaScopeInfo *LSI = PushLambdaScope();
15761  LSI->CallOperator = CallOperator;
15762  LSI->Lambda = LambdaClass;
15763  LSI->ReturnType = CallOperator->getReturnType();
15764  // This function in calls in situation where the context of the call operator
15765  // is not entered, so we set AfterParameterList to false, so that
15766  // `tryCaptureVariable` finds explicit captures in the appropriate context.
15767  LSI->AfterParameterList = false;
15768  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15769 
15770  if (LCD == LCD_None)
15772  else if (LCD == LCD_ByCopy)
15774  else if (LCD == LCD_ByRef)
15776  DeclarationNameInfo DNI = CallOperator->getNameInfo();
15777 
15779  LSI->Mutable = !CallOperator->isConst();
15780  if (CallOperator->isExplicitObjectMemberFunction())
15781  LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15782 
15783  // Add the captures to the LSI so they can be noted as already
15784  // captured within tryCaptureVar.
15785  auto I = LambdaClass->field_begin();
15786  for (const auto &C : LambdaClass->captures()) {
15787  if (C.capturesVariable()) {
15788  ValueDecl *VD = C.getCapturedVar();
15789  if (VD->isInitCapture())
15790  CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15791  const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15792  LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15793  /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15794  /*EllipsisLoc*/C.isPackExpansion()
15795  ? C.getEllipsisLoc() : SourceLocation(),
15796  I->getType(), /*Invalid*/false);
15797 
15798  } else if (C.capturesThis()) {
15799  LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15800  C.getCaptureKind() == LCK_StarThis);
15801  } else {
15802  LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15803  I->getType());
15804  }
15805  ++I;
15806  }
15807  return LSI;
15808 }
15809 
15811  SkipBodyInfo *SkipBody,
15812  FnBodyKind BodyKind) {
15813  if (!D) {
15814  // Parsing the function declaration failed in some way. Push on a fake scope
15815  // anyway so we can try to parse the function body.
15816  PushFunctionScope();
15817  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15818  return D;
15819  }
15820 
15821  FunctionDecl *FD = nullptr;
15822 
15823  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15824  FD = FunTmpl->getTemplatedDecl();
15825  else
15826  FD = cast<FunctionDecl>(D);
15827 
15828  // Do not push if it is a lambda because one is already pushed when building
15829  // the lambda in ActOnStartOfLambdaDefinition().
15830  if (!isLambdaCallOperator(FD))
15831  // [expr.const]/p14.1
15832  // An expression or conversion is in an immediate function context if it is
15833  // potentially evaluated and either: its innermost enclosing non-block scope
15834  // is a function parameter scope of an immediate function.
15835  PushExpressionEvaluationContext(
15836  FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15837  : ExprEvalContexts.back().Context);
15838 
15839  // Each ExpressionEvaluationContextRecord also keeps track of whether the
15840  // context is nested in an immediate function context, so smaller contexts
15841  // that appear inside immediate functions (like variable initializers) are
15842  // considered to be inside an immediate function context even though by
15843  // themselves they are not immediate function contexts. But when a new
15844  // function is entered, we need to reset this tracking, since the entered
15845  // function might be not an immediate function.
15846  ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15847  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15848  getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15849 
15850  // Check for defining attributes before the check for redefinition.
15851  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15852  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15853  FD->dropAttr<AliasAttr>();
15854  FD->setInvalidDecl();
15855  }
15856  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15857  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15858  FD->dropAttr<IFuncAttr>();
15859  FD->setInvalidDecl();
15860  }
15861  if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15862  if (!Context.getTargetInfo().hasFeature("fmv") &&
15863  !Attr->isDefaultVersion()) {
15864  // If function multi versioning disabled skip parsing function body
15865  // defined with non-default target_version attribute
15866  if (SkipBody)
15867  SkipBody->ShouldSkip = true;
15868  return nullptr;
15869  }
15870  }
15871 
15872  if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15873  if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15874  Ctor->isDefaultConstructor() &&
15875  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15876  // If this is an MS ABI dllexport default constructor, instantiate any
15877  // default arguments.
15878  InstantiateDefaultCtorDefaultArgs(Ctor);
15879  }
15880  }
15881 
15882  // See if this is a redefinition. If 'will have body' (or similar) is already
15883  // set, then these checks were already performed when it was set.
15884  if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15886  CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15887 
15888  // If we're skipping the body, we're done. Don't enter the scope.
15889  if (SkipBody && SkipBody->ShouldSkip)
15890  return D;
15891  }
15892 
15893  // Mark this function as "will have a body eventually". This lets users to
15894  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15895  // this function.
15896  FD->setWillHaveBody();
15897 
15898  // If we are instantiating a generic lambda call operator, push
15899  // a LambdaScopeInfo onto the function stack. But use the information
15900  // that's already been calculated (ActOnLambdaExpr) to prime the current
15901  // LambdaScopeInfo.
15902  // When the template operator is being specialized, the LambdaScopeInfo,
15903  // has to be properly restored so that tryCaptureVariable doesn't try
15904  // and capture any new variables. In addition when calculating potential
15905  // captures during transformation of nested lambdas, it is necessary to
15906  // have the LSI properly restored.
15908  // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15909  // instantiated, explicitly specialized.
15912  Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15913  FD->setInvalidDecl();
15914  PushFunctionScope();
15915  } else {
15916  assert(inTemplateInstantiation() &&
15917  "There should be an active template instantiation on the stack "
15918  "when instantiating a generic lambda!");
15919  RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15920  }
15921  } else {
15922  // Enter a new function scope
15923  PushFunctionScope();
15924  }
15925 
15926  // Builtin functions cannot be defined.
15927  if (unsigned BuiltinID = FD->getBuiltinID()) {
15928  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15929  !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15930  Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15931  FD->setInvalidDecl();
15932  }
15933  }
15934 
15935  // The return type of a function definition must be complete (C99 6.9.1p3).
15936  // C++23 [dcl.fct.def.general]/p2
15937  // The type of [...] the return for a function definition
15938  // shall not be a (possibly cv-qualified) class type that is incomplete
15939  // or abstract within the function body unless the function is deleted.
15940  QualType ResultType = FD->getReturnType();
15941  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15942  !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15943  (RequireCompleteType(FD->getLocation(), ResultType,
15944  diag::err_func_def_incomplete_result) ||
15945  RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15946  diag::err_abstract_type_in_decl,
15947  AbstractReturnType)))
15948  FD->setInvalidDecl();
15949 
15950  if (FnBodyScope)
15951  PushDeclContext(FnBodyScope, FD);
15952 
15953  // Check the validity of our function parameters
15954  if (BodyKind != FnBodyKind::Delete)
15955  CheckParmsForFunctionDef(FD->parameters(),
15956  /*CheckParameterNames=*/true);
15957 
15958  // Add non-parameter declarations already in the function to the current
15959  // scope.
15960  if (FnBodyScope) {
15961  for (Decl *NPD : FD->decls()) {
15962  auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15963  if (!NonParmDecl)
15964  continue;
15965  assert(!isa<ParmVarDecl>(NonParmDecl) &&
15966  "parameters should not be in newly created FD yet");
15967 
15968  // If the decl has a name, make it accessible in the current scope.
15969  if (NonParmDecl->getDeclName())
15970  PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15971 
15972  // Similarly, dive into enums and fish their constants out, making them
15973  // accessible in this scope.
15974  if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15975  for (auto *EI : ED->enumerators())
15976  PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15977  }
15978  }
15979  }
15980 
15981  // Introduce our parameters into the function scope
15982  for (auto *Param : FD->parameters()) {
15983  Param->setOwningFunction(FD);
15984 
15985  // If this has an identifier, add it to the scope stack.
15986  if (Param->getIdentifier() && FnBodyScope) {
15987  CheckShadow(FnBodyScope, Param);
15988 
15989  PushOnScopeChains(Param, FnBodyScope);
15990  }
15991  }
15992 
15993  // C++ [module.import/6] external definitions are not permitted in header
15994  // units. Deleted and Defaulted functions are implicitly inline (but the
15995  // inline state is not set at this point, so check the BodyKind explicitly).
15996  // FIXME: Consider an alternate location for the test where the inlined()
15997  // state is complete.
15998  if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15999  !FD->isInvalidDecl() && !FD->isInlined() &&
16000  BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16001  FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16002  !FD->isTemplateInstantiation()) {
16003  assert(FD->isThisDeclarationADefinition());
16004  Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16005  FD->setInvalidDecl();
16006  }
16007 
16008  // Ensure that the function's exception specification is instantiated.
16009  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16010  ResolveExceptionSpec(D->getLocation(), FPT);
16011 
16012  // dllimport cannot be applied to non-inline function definitions.
16013  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16014  !FD->isTemplateInstantiation()) {
16015  assert(!FD->hasAttr<DLLExportAttr>());
16016  Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16017  FD->setInvalidDecl();
16018  return D;
16019  }
16020 
16021  // Some function attributes (like OptimizeNoneAttr) need actions before
16022  // parsing body started.
16023  applyFunctionAttributesBeforeParsingBody(D);
16024 
16025  // We want to attach documentation to original Decl (which might be
16026  // a function template).
16027  ActOnDocumentableDecl(D);
16028  if (getCurLexicalContext()->isObjCContainer() &&
16029  getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16030  getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16031  Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16032 
16033  return D;
16034 }
16035 
16037  if (!FD || FD->isInvalidDecl())
16038  return;
16039  if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16040  FD = TD->getTemplatedDecl();
16041  if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16042  FPOptionsOverride FPO;
16044  CurFPFeatures.applyChanges(FPO);
16045  FpPragmaStack.CurrentValue =
16046  CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16047  }
16048 }
16049 
16050 /// Given the set of return statements within a function body,
16051 /// compute the variables that are subject to the named return value
16052 /// optimization.
16053 ///
16054 /// Each of the variables that is subject to the named return value
16055 /// optimization will be marked as NRVO variables in the AST, and any
16056 /// return statement that has a marked NRVO variable as its NRVO candidate can
16057 /// use the named return value optimization.
16058 ///
16059 /// This function applies a very simplistic algorithm for NRVO: if every return
16060 /// statement in the scope of a variable has the same NRVO candidate, that
16061 /// candidate is an NRVO variable.
16063  ReturnStmt **Returns = Scope->Returns.data();
16064 
16065  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16066  if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16067  if (!NRVOCandidate->isNRVOVariable())
16068  Returns[I]->setNRVOCandidate(nullptr);
16069  }
16070  }
16071 }
16072 
16074  // We can't delay parsing the body of a constexpr function template (yet).
16076  return false;
16077 
16078  // We can't delay parsing the body of a function template with a deduced
16079  // return type (yet).
16080  if (D.getDeclSpec().hasAutoTypeSpec()) {
16081  // If the placeholder introduces a non-deduced trailing return type,
16082  // we can still delay parsing it.
16083  if (D.getNumTypeObjects()) {
16084  const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16085  if (Outer.Kind == DeclaratorChunk::Function &&
16086  Outer.Fun.hasTrailingReturnType()) {
16087  QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16088  return Ty.isNull() || !Ty->isUndeducedType();
16089  }
16090  }
16091  return false;
16092  }
16093 
16094  return true;
16095 }
16096 
16098  // We cannot skip the body of a function (or function template) which is
16099  // constexpr, since we may need to evaluate its body in order to parse the
16100  // rest of the file.
16101  // We cannot skip the body of a function with an undeduced return type,
16102  // because any callers of that function need to know the type.
16103  if (const FunctionDecl *FD = D->getAsFunction()) {
16104  if (FD->isConstexpr())
16105  return false;
16106  // We can't simply call Type::isUndeducedType here, because inside template
16107  // auto can be deduced to a dependent type, which is not considered
16108  // "undeduced".
16109  if (FD->getReturnType()->getContainedDeducedType())
16110  return false;
16111  }
16112  return Consumer.shouldSkipFunctionBody(D);
16113 }
16114 
16116  if (!Decl)
16117  return nullptr;
16118  if (FunctionDecl *FD = Decl->getAsFunction())
16119  FD->setHasSkippedBody();
16120  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16121  MD->setHasSkippedBody();
16122  return Decl;
16123 }
16124 
16126  return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
16127 }
16128 
16129 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
16130 /// body.
16132 public:
16133  ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16135  if (!IsLambda)
16137  }
16138 
16139 private:
16140  Sema &S;
16141  bool IsLambda = false;
16142 };
16143 
16145  llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16146 
16147  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16148  if (EscapeInfo.count(BD))
16149  return EscapeInfo[BD];
16150 
16151  bool R = false;
16152  const BlockDecl *CurBD = BD;
16153 
16154  do {
16155  R = !CurBD->doesNotEscape();
16156  if (R)
16157  break;
16158  CurBD = CurBD->getParent()->getInnermostBlockDecl();
16159  } while (CurBD);
16160 
16161  return EscapeInfo[BD] = R;
16162  };
16163 
16164  // If the location where 'self' is implicitly retained is inside a escaping
16165  // block, emit a diagnostic.
16166  for (const std::pair<SourceLocation, const BlockDecl *> &P :
16168  if (IsOrNestedInEscapingBlock(P.second))
16169  S.Diag(P.first, diag::warn_implicitly_retains_self)
16170  << FixItHint::CreateInsertion(P.first, "self->");
16171 }
16172 
16173 static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16174  return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16175  FD->getDeclName().isIdentifier() && FD->getName().equals(Name);
16176 }
16177 
16179  return methodHasName(FD, "get_return_object");
16180 }
16181 
16183  return FD->isStatic() &&
16184  methodHasName(FD, "get_return_object_on_allocation_failure");
16185 }
16186 
16188  RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16189  if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16190  return;
16191  // Allow some_promise_type::get_return_object().
16192  if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16193  return;
16194  if (!FD->hasAttr<CoroWrapperAttr>())
16195  Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16196 }
16197 
16199  bool IsInstantiation) {
16200  FunctionScopeInfo *FSI = getCurFunction();
16201  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16202 
16203  if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16204  FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16205 
16206  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16207  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16208 
16209  // If we skip function body, we can't tell if a function is a coroutine.
16210  if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16211  if (FSI->isCoroutine())
16212  CheckCompletedCoroutineBody(FD, Body);
16213  else
16214  CheckCoroutineWrapper(FD);
16215  }
16216 
16217  {
16218  // Do not call PopExpressionEvaluationContext() if it is a lambda because
16219  // one is already popped when finishing the lambda in BuildLambdaExpr().
16220  // This is meant to pop the context added in ActOnStartOfFunctionDef().
16221  ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16222  if (FD) {
16223  // If this is called by Parser::ParseFunctionDefinition() after marking
16224  // the declaration as deleted, and if the deleted-function-body contains
16225  // a message (C++26), then a DefaultedOrDeletedInfo will have already been
16226  // added to store that message; do not overwrite it in that case.
16227  //
16228  // Since this would always set the body to 'nullptr' in that case anyway,
16229  // which is already done when the function decl is initially created,
16230  // always skipping this irrespective of whether there is a delete message
16231  // should not be a problem.
16232  if (!FD->isDeletedAsWritten())
16233  FD->setBody(Body);
16234  FD->setWillHaveBody(false);
16235  CheckImmediateEscalatingFunctionDefinition(FD, FSI);
16236 
16237  if (getLangOpts().CPlusPlus14) {
16238  if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16239  FD->getReturnType()->isUndeducedType()) {
16240  // For a function with a deduced result type to return void,
16241  // the result type as written must be 'auto' or 'decltype(auto)',
16242  // possibly cv-qualified or constrained, but not ref-qualified.
16243  if (!FD->getReturnType()->getAs<AutoType>()) {
16244  Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16245  << FD->getReturnType();
16246  FD->setInvalidDecl();
16247  } else {
16248  // Falling off the end of the function is the same as 'return;'.
16249  Expr *Dummy = nullptr;
16250  if (DeduceFunctionTypeFromReturnExpr(
16251  FD, dcl->getLocation(), Dummy,
16252  FD->getReturnType()->getAs<AutoType>()))
16253  FD->setInvalidDecl();
16254  }
16255  }
16256  } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16257  // In C++11, we don't use 'auto' deduction rules for lambda call
16258  // operators because we don't support return type deduction.
16259  auto *LSI = getCurLambda();
16260  if (LSI->HasImplicitReturnType) {
16261  deduceClosureReturnType(*LSI);
16262 
16263  // C++11 [expr.prim.lambda]p4:
16264  // [...] if there are no return statements in the compound-statement
16265  // [the deduced type is] the type void
16266  QualType RetType =
16267  LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16268 
16269  // Update the return type to the deduced type.
16270  const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16271  FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16272  Proto->getExtProtoInfo()));
16273  }
16274  }
16275 
16276  // If the function implicitly returns zero (like 'main') or is naked,
16277  // don't complain about missing return statements.
16278  if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16280 
16281  // MSVC permits the use of pure specifier (=0) on function definition,
16282  // defined at class scope, warn about this non-standard construct.
16283  if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16284  !FD->isOutOfLine())
16285  Diag(FD->getLocation(), diag::ext_pure_function_definition);
16286 
16287  if (!FD->isInvalidDecl()) {
16288  // Don't diagnose unused parameters of defaulted, deleted or naked
16289  // functions.
16290  if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16291  !FD->hasAttr<NakedAttr>())
16292  DiagnoseUnusedParameters(FD->parameters());
16293  DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
16294  FD->getReturnType(), FD);
16295 
16296  // If this is a structor, we need a vtable.
16297  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16298  MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16299  else if (CXXDestructorDecl *Destructor =
16300  dyn_cast<CXXDestructorDecl>(FD))
16301  MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16302 
16303  // Try to apply the named return value optimization. We have to check
16304  // if we can do this here because lambdas keep return statements around
16305  // to deduce an implicit return type.
16306  if (FD->getReturnType()->isRecordType() &&
16307  (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16308  computeNRVO(Body, FSI);
16309  }
16310 
16311  // GNU warning -Wmissing-prototypes:
16312  // Warn if a global function is defined without a previous
16313  // prototype declaration. This warning is issued even if the
16314  // definition itself provides a prototype. The aim is to detect
16315  // global functions that fail to be declared in header files.
16316  const FunctionDecl *PossiblePrototype = nullptr;
16317  if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16318  Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16319 
16320  if (PossiblePrototype) {
16321  // We found a declaration that is not a prototype,
16322  // but that could be a zero-parameter prototype
16323  if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16324  TypeLoc TL = TI->getTypeLoc();
16326  Diag(PossiblePrototype->getLocation(),
16327  diag::note_declaration_not_a_prototype)
16328  << (FD->getNumParams() != 0)
16329  << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16330  FTL.getRParenLoc(), "void")
16331  : FixItHint{});
16332  }
16333  } else {
16334  // Returns true if the token beginning at this Loc is `const`.
16335  auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16336  const LangOptions &LangOpts) {
16337  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16338  if (LocInfo.first.isInvalid())
16339  return false;
16340 
16341  bool Invalid = false;
16342  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16343  if (Invalid)
16344  return false;
16345 
16346  if (LocInfo.second > Buffer.size())
16347  return false;
16348 
16349  const char *LexStart = Buffer.data() + LocInfo.second;
16350  StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16351 
16352  return StartTok.consume_front("const") &&
16353  (StartTok.empty() || isWhitespace(StartTok[0]) ||
16354  StartTok.starts_with("/*") || StartTok.starts_with("//"));
16355  };
16356 
16357  auto findBeginLoc = [&]() {
16358  // If the return type has `const` qualifier, we want to insert
16359  // `static` before `const` (and not before the typename).
16360  if ((FD->getReturnType()->isAnyPointerType() &&
16362  FD->getReturnType().isConstQualified()) {
16363  // But only do this if we can determine where the `const` is.
16364 
16365  if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16366  getLangOpts()))
16367 
16368  return FD->getBeginLoc();
16369  }
16370  return FD->getTypeSpecStartLoc();
16371  };
16372  Diag(FD->getTypeSpecStartLoc(),
16373  diag::note_static_for_internal_linkage)
16374  << /* function */ 1
16375  << (FD->getStorageClass() == SC_None
16376  ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16377  : FixItHint{});
16378  }
16379  }
16380 
16381  // We might not have found a prototype because we didn't wish to warn on
16382  // the lack of a missing prototype. Try again without the checks for
16383  // whether we want to warn on the missing prototype.
16384  if (!PossiblePrototype)
16385  (void)FindPossiblePrototype(FD, PossiblePrototype);
16386 
16387  // If the function being defined does not have a prototype, then we may
16388  // need to diagnose it as changing behavior in C23 because we now know
16389  // whether the function accepts arguments or not. This only handles the
16390  // case where the definition has no prototype but does have parameters
16391  // and either there is no previous potential prototype, or the previous
16392  // potential prototype also has no actual prototype. This handles cases
16393  // like:
16394  // void f(); void f(a) int a; {}
16395  // void g(a) int a; {}
16396  // See MergeFunctionDecl() for other cases of the behavior change
16397  // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16398  // type without a prototype.
16399  if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16400  (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16401  !PossiblePrototype->isImplicit()))) {
16402  // The function definition has parameters, so this will change behavior
16403  // in C23. If there is a possible prototype, it comes before the
16404  // function definition.
16405  // FIXME: The declaration may have already been diagnosed as being
16406  // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16407  // there's no way to test for the "changes behavior" condition in
16408  // SemaType.cpp when forming the declaration's function type. So, we do
16409  // this awkward dance instead.
16410  //
16411  // If we have a possible prototype and it declares a function with a
16412  // prototype, we don't want to diagnose it; if we have a possible
16413  // prototype and it has no prototype, it may have already been
16414  // diagnosed in SemaType.cpp as deprecated depending on whether
16415  // -Wstrict-prototypes is enabled. If we already warned about it being
16416  // deprecated, add a note that it also changes behavior. If we didn't
16417  // warn about it being deprecated (because the diagnostic is not
16418  // enabled), warn now that it is deprecated and changes behavior.
16419 
16420  // This K&R C function definition definitely changes behavior in C23,
16421  // so diagnose it.
16422  Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16423  << /*definition*/ 1 << /* not supported in C23 */ 0;
16424 
16425  // If we have a possible prototype for the function which is a user-
16426  // visible declaration, we already tested that it has no prototype.
16427  // This will change behavior in C23. This gets a warning rather than a
16428  // note because it's the same behavior-changing problem as with the
16429  // definition.
16430  if (PossiblePrototype)
16431  Diag(PossiblePrototype->getLocation(),
16432  diag::warn_non_prototype_changes_behavior)
16433  << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16434  << /*definition*/ 1;
16435  }
16436 
16437  // Warn on CPUDispatch with an actual body.
16438  if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16439  if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16440  if (!CmpndBody->body_empty())
16441  Diag(CmpndBody->body_front()->getBeginLoc(),
16442  diag::warn_dispatch_body_ignored);
16443 
16444  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16445  const CXXMethodDecl *KeyFunction;
16446  if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16447  MD->isVirtual() &&
16448  (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16449  MD == KeyFunction->getCanonicalDecl()) {
16450  // Update the key-function state if necessary for this ABI.
16451  if (FD->isInlined() &&
16453  Context.setNonKeyFunction(MD);
16454 
16455  // If the newly-chosen key function is already defined, then we
16456  // need to mark the vtable as used retroactively.
16457  KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16458  const FunctionDecl *Definition;
16459  if (KeyFunction && KeyFunction->isDefined(Definition))
16460  MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16461  } else {
16462  // We just defined they key function; mark the vtable as used.
16463  MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16464  }
16465  }
16466  }
16467 
16468  assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16469  "Function parsing confused");
16470  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16471  assert(MD == getCurMethodDecl() && "Method parsing confused");
16472  MD->setBody(Body);
16473  if (!MD->isInvalidDecl()) {
16474  DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16475  MD->getReturnType(), MD);
16476 
16477  if (Body)
16478  computeNRVO(Body, FSI);
16479  }
16480  if (FSI->ObjCShouldCallSuper) {
16481  Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16482  << MD->getSelector().getAsString();
16483  FSI->ObjCShouldCallSuper = false;
16484  }
16486  const ObjCMethodDecl *InitMethod = nullptr;
16487  bool isDesignated =
16488  MD->isDesignatedInitializerForTheInterface(&InitMethod);
16489  assert(isDesignated && InitMethod);
16490  (void)isDesignated;
16491 
16492  auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16493  auto IFace = MD->getClassInterface();
16494  if (!IFace)
16495  return false;
16496  auto SuperD = IFace->getSuperClass();
16497  if (!SuperD)
16498  return false;
16499  return SuperD->getIdentifier() ==
16500  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16501  };
16502  // Don't issue this warning for unavailable inits or direct subclasses
16503  // of NSObject.
16504  if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16505  Diag(MD->getLocation(),
16506  diag::warn_objc_designated_init_missing_super_call);
16507  Diag(InitMethod->getLocation(),
16508  diag::note_objc_designated_init_marked_here);
16509  }
16510  FSI->ObjCWarnForNoDesignatedInitChain = false;
16511  }
16512  if (FSI->ObjCWarnForNoInitDelegation) {
16513  // Don't issue this warning for unavaialable inits.
16514  if (!MD->isUnavailable())
16515  Diag(MD->getLocation(),
16516  diag::warn_objc_secondary_init_missing_init_call);
16517  FSI->ObjCWarnForNoInitDelegation = false;
16518  }
16519 
16521  } else {
16522  // Parsing the function declaration failed in some way. Pop the fake scope
16523  // we pushed on.
16524  PopFunctionScopeInfo(ActivePolicy, dcl);
16525  return nullptr;
16526  }
16527 
16528  if (Body && FSI->HasPotentialAvailabilityViolations)
16529  DiagnoseUnguardedAvailabilityViolations(dcl);
16530 
16531  assert(!FSI->ObjCShouldCallSuper &&
16532  "This should only be set for ObjC methods, which should have been "
16533  "handled in the block above.");
16534 
16535  // Verify and clean out per-function state.
16536  if (Body && (!FD || !FD->isDefaulted())) {
16537  // C++ constructors that have function-try-blocks can't have return
16538  // statements in the handlers of that block. (C++ [except.handle]p14)
16539  // Verify this.
16540  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16541  DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16542 
16543  // Verify that gotos and switch cases don't jump into scopes illegally.
16544  if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16545  DiagnoseInvalidJumps(Body);
16546 
16547  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16548  if (!Destructor->getParent()->isDependentType())
16549  CheckDestructor(Destructor);
16550 
16551  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16552  Destructor->getParent());
16553  }
16554 
16555  // If any errors have occurred, clear out any temporaries that may have
16556  // been leftover. This ensures that these temporaries won't be picked up
16557  // for deletion in some later function.
16558  if (hasUncompilableErrorOccurred() ||
16559  hasAnyUnrecoverableErrorsInThisFunction() ||
16560  getDiagnostics().getSuppressAllDiagnostics()) {
16561  DiscardCleanupsInEvaluationContext();
16562  }
16563  if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16564  // Since the body is valid, issue any analysis-based warnings that are
16565  // enabled.
16566  ActivePolicy = &WP;
16567  }
16568 
16569  if (!IsInstantiation && FD &&
16570  (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16571  !FD->isInvalidDecl() &&
16572  !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16573  FD->setInvalidDecl();
16574 
16575  if (FD && FD->hasAttr<NakedAttr>()) {
16576  for (const Stmt *S : Body->children()) {
16577  // Allow local register variables without initializer as they don't
16578  // require prologue.
16579  bool RegisterVariables = false;
16580  if (auto *DS = dyn_cast<DeclStmt>(S)) {
16581  for (const auto *Decl : DS->decls()) {
16582  if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16583  RegisterVariables =
16584  Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16585  if (!RegisterVariables)
16586  break;
16587  }
16588  }
16589  }
16590  if (RegisterVariables)
16591  continue;
16592  if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16593  Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16594  Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16595  FD->setInvalidDecl();
16596  break;
16597  }
16598  }
16599  }
16600 
16601  assert(ExprCleanupObjects.size() ==
16602  ExprEvalContexts.back().NumCleanupObjects &&
16603  "Leftover temporaries in function");
16604  assert(!Cleanup.exprNeedsCleanups() &&
16605  "Unaccounted cleanups in function");
16606  assert(MaybeODRUseExprs.empty() &&
16607  "Leftover expressions for odr-use checking");
16608  }
16609  } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16610  // the declaration context below. Otherwise, we're unable to transform
16611  // 'this' expressions when transforming immediate context functions.
16612 
16613  if (!IsInstantiation)
16614  PopDeclContext();
16615 
16616  PopFunctionScopeInfo(ActivePolicy, dcl);
16617  // If any errors have occurred, clear out any temporaries that may have
16618  // been leftover. This ensures that these temporaries won't be picked up for
16619  // deletion in some later function.
16620  if (hasUncompilableErrorOccurred()) {
16621  DiscardCleanupsInEvaluationContext();
16622  }
16623 
16624  if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16625  !LangOpts.OMPTargetTriples.empty())) ||
16626  LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16627  auto ES = getEmissionStatus(FD);
16630  DeclsToCheckForDeferredDiags.insert(FD);
16631  }
16632 
16633  if (FD && !FD->isDeleted())
16634  checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16635 
16636  return dcl;
16637 }
16638 
16639 /// When we finish delayed parsing of an attribute, we must attach it to the
16640 /// relevant Decl.
16642  ParsedAttributes &Attrs) {
16643  // Always attach attributes to the underlying decl.
16644  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16645  D = TD->getTemplatedDecl();
16646  ProcessDeclAttributeList(S, D, Attrs);
16647  ProcessAPINotes(D);
16648 
16649  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16650  if (Method->isStatic())
16651  checkThisInStaticMemberFunctionAttributes(Method);
16652 }
16653 
16654 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16655 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16657  IdentifierInfo &II, Scope *S) {
16658  // It is not valid to implicitly define a function in C23.
16659  assert(LangOpts.implicitFunctionsAllowed() &&
16660  "Implicit function declarations aren't allowed in this language mode");
16661 
16662  // Find the scope in which the identifier is injected and the corresponding
16663  // DeclContext.
16664  // FIXME: C89 does not say what happens if there is no enclosing block scope.
16665  // In that case, we inject the declaration into the translation unit scope
16666  // instead.
16667  Scope *BlockScope = S;
16668  while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16669  BlockScope = BlockScope->getParent();
16670 
16671  // Loop until we find a DeclContext that is either a function/method or the
16672  // translation unit, which are the only two valid places to implicitly define
16673  // a function. This avoids accidentally defining the function within a tag
16674  // declaration, for example.
16675  Scope *ContextScope = BlockScope;
16676  while (!ContextScope->getEntity() ||
16677  (!ContextScope->getEntity()->isFunctionOrMethod() &&
16678  !ContextScope->getEntity()->isTranslationUnit()))
16679  ContextScope = ContextScope->getParent();
16680  ContextRAII SavedContext(*this, ContextScope->getEntity());
16681 
16682  // Before we produce a declaration for an implicitly defined
16683  // function, see whether there was a locally-scoped declaration of
16684  // this name as a function or variable. If so, use that
16685  // (non-visible) declaration, and complain about it.
16686  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16687  if (ExternCPrev) {
16688  // We still need to inject the function into the enclosing block scope so
16689  // that later (non-call) uses can see it.
16690  PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16691 
16692  // C89 footnote 38:
16693  // If in fact it is not defined as having type "function returning int",
16694  // the behavior is undefined.
16695  if (!isa<FunctionDecl>(ExternCPrev) ||
16696  !Context.typesAreCompatible(
16697  cast<FunctionDecl>(ExternCPrev)->getType(),
16698  Context.getFunctionNoProtoType(Context.IntTy))) {
16699  Diag(Loc, diag::ext_use_out_of_scope_declaration)
16700  << ExternCPrev << !getLangOpts().C99;
16701  Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16702  return ExternCPrev;
16703  }
16704  }
16705 
16706  // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16707  unsigned diag_id;
16708  if (II.getName().starts_with("__builtin_"))
16709  diag_id = diag::warn_builtin_unknown;
16710  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16711  else if (getLangOpts().C99)
16712  diag_id = diag::ext_implicit_function_decl_c99;
16713  else
16714  diag_id = diag::warn_implicit_function_decl;
16715 
16716  TypoCorrection Corrected;
16717  // Because typo correction is expensive, only do it if the implicit
16718  // function declaration is going to be treated as an error.
16719  //
16720  // Perform the correction before issuing the main diagnostic, as some
16721  // consumers use typo-correction callbacks to enhance the main diagnostic.
16722  if (S && !ExternCPrev &&
16723  (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16725  Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16726  S, nullptr, CCC, CTK_NonError);
16727  }
16728 
16729  Diag(Loc, diag_id) << &II;
16730  if (Corrected) {
16731  // If the correction is going to suggest an implicitly defined function,
16732  // skip the correction as not being a particularly good idea.
16733  bool Diagnose = true;
16734  if (const auto *D = Corrected.getCorrectionDecl())
16735  Diagnose = !D->isImplicit();
16736  if (Diagnose)
16737  diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16738  /*ErrorRecovery*/ false);
16739  }
16740 
16741  // If we found a prior declaration of this function, don't bother building
16742  // another one. We've already pushed that one into scope, so there's nothing
16743  // more to do.
16744  if (ExternCPrev)
16745  return ExternCPrev;
16746 
16747  // Set a Declarator for the implicit definition: int foo();
16748  const char *Dummy;
16749  AttributeFactory attrFactory;
16750  DeclSpec DS(attrFactory);
16751  unsigned DiagID;
16752  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16753  Context.getPrintingPolicy());
16754  (void)Error; // Silence warning.
16755  assert(!Error && "Error setting up implicit decl!");
16756  SourceLocation NoLoc;
16758  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16759  /*IsAmbiguous=*/false,
16760  /*LParenLoc=*/NoLoc,
16761  /*Params=*/nullptr,
16762  /*NumParams=*/0,
16763  /*EllipsisLoc=*/NoLoc,
16764  /*RParenLoc=*/NoLoc,
16765  /*RefQualifierIsLvalueRef=*/true,
16766  /*RefQualifierLoc=*/NoLoc,
16767  /*MutableLoc=*/NoLoc, EST_None,
16768  /*ESpecRange=*/SourceRange(),
16769  /*Exceptions=*/nullptr,
16770  /*ExceptionRanges=*/nullptr,
16771  /*NumExceptions=*/0,
16772  /*NoexceptExpr=*/nullptr,
16773  /*ExceptionSpecTokens=*/nullptr,
16774  /*DeclsInPrototype=*/std::nullopt,
16775  Loc, Loc, D),
16776  std::move(DS.getAttributes()), SourceLocation());
16777  D.SetIdentifier(&II, Loc);
16778 
16779  // Insert this function into the enclosing block scope.
16780  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16781  FD->setImplicit();
16782 
16783  AddKnownFunctionAttributes(FD);
16784 
16785  return FD;
16786 }
16787 
16788 /// If this function is a C++ replaceable global allocation function
16789 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16790 /// adds any function attributes that we know a priori based on the standard.
16791 ///
16792 /// We need to check for duplicate attributes both here and where user-written
16793 /// attributes are applied to declarations.
16795  FunctionDecl *FD) {
16796  if (FD->isInvalidDecl())
16797  return;
16798 
16799  if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16800  FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16801  return;
16802 
16803  std::optional<unsigned> AlignmentParam;
16804  bool IsNothrow = false;
16805  if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16806  return;
16807 
16808  // C++2a [basic.stc.dynamic.allocation]p4:
16809  // An allocation function that has a non-throwing exception specification
16810  // indicates failure by returning a null pointer value. Any other allocation
16811  // function never returns a null pointer value and indicates failure only by
16812  // throwing an exception [...]
16813  //
16814  // However, -fcheck-new invalidates this possible assumption, so don't add
16815  // NonNull when that is enabled.
16816  if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16817  !getLangOpts().CheckNew)
16818  FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16819 
16820  // C++2a [basic.stc.dynamic.allocation]p2:
16821  // An allocation function attempts to allocate the requested amount of
16822  // storage. [...] If the request succeeds, the value returned by a
16823  // replaceable allocation function is a [...] pointer value p0 different
16824  // from any previously returned value p1 [...]
16825  //
16826  // However, this particular information is being added in codegen,
16827  // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16828 
16829  // C++2a [basic.stc.dynamic.allocation]p2:
16830  // An allocation function attempts to allocate the requested amount of
16831  // storage. If it is successful, it returns the address of the start of a
16832  // block of storage whose length in bytes is at least as large as the
16833  // requested size.
16834  if (!FD->hasAttr<AllocSizeAttr>()) {
16835  FD->addAttr(AllocSizeAttr::CreateImplicit(
16836  Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16837  /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16838  }
16839 
16840  // C++2a [basic.stc.dynamic.allocation]p3:
16841  // For an allocation function [...], the pointer returned on a successful
16842  // call shall represent the address of storage that is aligned as follows:
16843  // (3.1) If the allocation function takes an argument of type
16844  // std​::​align_­val_­t, the storage will have the alignment
16845  // specified by the value of this argument.
16846  if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16847  FD->addAttr(AllocAlignAttr::CreateImplicit(
16848  Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16849  }
16850 
16851  // FIXME:
16852  // C++2a [basic.stc.dynamic.allocation]p3:
16853  // For an allocation function [...], the pointer returned on a successful
16854  // call shall represent the address of storage that is aligned as follows:
16855  // (3.2) Otherwise, if the allocation function is named operator new[],
16856  // the storage is aligned for any object that does not have
16857  // new-extended alignment ([basic.align]) and is no larger than the
16858  // requested size.
16859  // (3.3) Otherwise, the storage is aligned for any object that does not
16860  // have new-extended alignment and is of the requested size.
16861 }
16862 
16863 /// Adds any function attributes that we know a priori based on
16864 /// the declaration of this function.
16865 ///
16866 /// These attributes can apply both to implicitly-declared builtins
16867 /// (like __builtin___printf_chk) or to library-declared functions
16868 /// like NSLog or printf.
16869 ///
16870 /// We need to check for duplicate attributes both here and where user-written
16871 /// attributes are applied to declarations.
16873  if (FD->isInvalidDecl())
16874  return;
16875 
16876  // If this is a built-in function, map its builtin attributes to
16877  // actual attributes.
16878  if (unsigned BuiltinID = FD->getBuiltinID()) {
16879  // Handle printf-formatting attributes.
16880  unsigned FormatIdx;
16881  bool HasVAListArg;
16882  if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16883  if (!FD->hasAttr<FormatAttr>()) {
16884  const char *fmt = "printf";
16885  unsigned int NumParams = FD->getNumParams();
16886  if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16887  FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16888  fmt = "NSString";
16889  FD->addAttr(FormatAttr::CreateImplicit(Context,
16890  &Context.Idents.get(fmt),
16891  FormatIdx+1,
16892  HasVAListArg ? 0 : FormatIdx+2,
16893  FD->getLocation()));
16894  }
16895  }
16896  if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16897  HasVAListArg)) {
16898  if (!FD->hasAttr<FormatAttr>())
16899  FD->addAttr(FormatAttr::CreateImplicit(Context,
16900  &Context.Idents.get("scanf"),
16901  FormatIdx+1,
16902  HasVAListArg ? 0 : FormatIdx+2,
16903  FD->getLocation()));
16904  }
16905 
16906  // Handle automatically recognized callbacks.
16908  if (!FD->hasAttr<CallbackAttr>() &&
16909  Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16910  FD->addAttr(CallbackAttr::CreateImplicit(
16911  Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16912 
16913  // Mark const if we don't care about errno and/or floating point exceptions
16914  // that are the only thing preventing the function from being const. This
16915  // allows IRgen to use LLVM intrinsics for such functions.
16916  bool NoExceptions =
16917  getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16918  bool ConstWithoutErrnoAndExceptions =
16919  Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16920  bool ConstWithoutExceptions =
16921  Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16922  if (!FD->hasAttr<ConstAttr>() &&
16923  (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16924  (!ConstWithoutErrnoAndExceptions ||
16925  (!getLangOpts().MathErrno && NoExceptions)) &&
16926  (!ConstWithoutExceptions || NoExceptions))
16927  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16928 
16929  // We make "fma" on GNU or Windows const because we know it does not set
16930  // errno in those environments even though it could set errno based on the
16931  // C standard.
16932  const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16933  if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16934  !FD->hasAttr<ConstAttr>()) {
16935  switch (BuiltinID) {
16936  case Builtin::BI__builtin_fma:
16937  case Builtin::BI__builtin_fmaf:
16938  case Builtin::BI__builtin_fmal:
16939  case Builtin::BIfma:
16940  case Builtin::BIfmaf:
16941  case Builtin::BIfmal:
16942  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16943  break;
16944  default:
16945  break;
16946  }
16947  }
16948 
16949  if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16950  !FD->hasAttr<ReturnsTwiceAttr>())
16951  FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16952  FD->getLocation()));
16953  if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16954  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16955  if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16956  FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16957  if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16958  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16959  if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16960  !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16961  // Add the appropriate attribute, depending on the CUDA compilation mode
16962  // and which target the builtin belongs to. For example, during host
16963  // compilation, aux builtins are __device__, while the rest are __host__.
16964  if (((getLangOpts().SYCLIsDevice && getLangOpts().CUDA &&
16965  !getLangOpts().CUDAIsDevice) ||
16966  getLangOpts().CUDAIsDevice) !=
16967  Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16968  FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16969  else
16970  FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16971  }
16972 
16973  // Add known guaranteed alignment for allocation functions.
16974  switch (BuiltinID) {
16975  case Builtin::BImemalign:
16976  case Builtin::BIaligned_alloc:
16977  if (!FD->hasAttr<AllocAlignAttr>())
16978  FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16979  FD->getLocation()));
16980  break;
16981  default:
16982  break;
16983  }
16984 
16985  // Add allocsize attribute for allocation functions.
16986  switch (BuiltinID) {
16987  case Builtin::BIcalloc:
16988  FD->addAttr(AllocSizeAttr::CreateImplicit(
16989  Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16990  break;
16991  case Builtin::BImemalign:
16992  case Builtin::BIaligned_alloc:
16993  case Builtin::BIrealloc:
16994  FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16995  ParamIdx(), FD->getLocation()));
16996  break;
16997  case Builtin::BImalloc:
16998  FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16999  ParamIdx(), FD->getLocation()));
17000  break;
17001  default:
17002  break;
17003  }
17004 
17005  // Add lifetime attribute to std::move, std::fowrard et al.
17006  switch (BuiltinID) {
17007  case Builtin::BIaddressof:
17008  case Builtin::BI__addressof:
17009  case Builtin::BI__builtin_addressof:
17010  case Builtin::BIas_const:
17011  case Builtin::BIforward:
17012  case Builtin::BIforward_like:
17013  case Builtin::BImove:
17014  case Builtin::BImove_if_noexcept:
17015  if (ParmVarDecl *P = FD->getParamDecl(0u);
17016  !P->hasAttr<LifetimeBoundAttr>())
17017  P->addAttr(
17018  LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
17019  break;
17020  default:
17021  break;
17022  }
17023  }
17024 
17025  AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17026 
17027  // If C++ exceptions are enabled but we are told extern "C" functions cannot
17028  // throw, add an implicit nothrow attribute to any extern "C" function we come
17029  // across.
17030  if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17031  FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17032  const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17033  if (!FPT || FPT->getExceptionSpecType() == EST_None)
17034  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17035  }
17036 
17037  IdentifierInfo *Name = FD->getIdentifier();
17038  if (!Name)
17039  return;
17040  if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17041  (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
17042  cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17044  // Okay: this could be a libc/libm/Objective-C function we know
17045  // about.
17046  } else
17047  return;
17048 
17049  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17050  // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17051  // target-specific builtins, perhaps?
17052  if (!FD->hasAttr<FormatAttr>())
17053  FD->addAttr(FormatAttr::CreateImplicit(Context,
17054  &Context.Idents.get("printf"), 2,
17055  Name->isStr("vasprintf") ? 0 : 3,
17056  FD->getLocation()));
17057  }
17058 
17059  if (Name->isStr("__CFStringMakeConstantString")) {
17060  // We already have a __builtin___CFStringMakeConstantString,
17061  // but builds that use -fno-constant-cfstrings don't go through that.
17062  if (!FD->hasAttr<FormatArgAttr>())
17063  FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17064  FD->getLocation()));
17065  }
17066 }
17067 
17069  TypeSourceInfo *TInfo) {
17070  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17071  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17072 
17073  if (!TInfo) {
17074  assert(D.isInvalidType() && "no declarator info for valid type");
17075  TInfo = Context.getTrivialTypeSourceInfo(T);
17076  }
17077 
17078  // Scope manipulation handled by caller.
17079  TypedefDecl *NewTD =
17080  TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
17081  D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17082 
17083  // Bail out immediately if we have an invalid declaration.
17084  if (D.isInvalidType()) {
17085  NewTD->setInvalidDecl();
17086  return NewTD;
17087  }
17088 
17090  if (CurContext->isFunctionOrMethod())
17091  Diag(NewTD->getLocation(), diag::err_module_private_local)
17092  << 2 << NewTD
17096  else
17097  NewTD->setModulePrivate();
17098  }
17099 
17100  // C++ [dcl.typedef]p8:
17101  // If the typedef declaration defines an unnamed class (or
17102  // enum), the first typedef-name declared by the declaration
17103  // to be that class type (or enum type) is used to denote the
17104  // class type (or enum type) for linkage purposes only.
17105  // We need to check whether the type was declared in the declaration.
17106  switch (D.getDeclSpec().getTypeSpecType()) {
17107  case TST_enum:
17108  case TST_struct:
17109  case TST_interface:
17110  case TST_union:
17111  case TST_class: {
17112  TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17113  setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17114  break;
17115  }
17116 
17117  default:
17118  break;
17119  }
17120 
17121  return NewTD;
17122 }
17123 
17124 /// Check that this is a valid underlying type for an enum declaration.
17126  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17127  QualType T = TI->getType();
17128 
17129  if (T->isDependentType())
17130  return false;
17131 
17132  // This doesn't use 'isIntegralType' despite the error message mentioning
17133  // integral type because isIntegralType would also allow enum types in C.
17134  if (const BuiltinType *BT = T->getAs<BuiltinType>())
17135  if (BT->isInteger())
17136  return false;
17137 
17138  return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17139  << T << T->isBitIntType();
17140 }
17141 
17142 /// Check whether this is a valid redeclaration of a previous enumeration.
17143 /// \return true if the redeclaration was invalid.
17144 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17145  QualType EnumUnderlyingTy, bool IsFixed,
17146  const EnumDecl *Prev) {
17147  if (IsScoped != Prev->isScoped()) {
17148  Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17149  << Prev->isScoped();
17150  Diag(Prev->getLocation(), diag::note_previous_declaration);
17151  return true;
17152  }
17153 
17154  if (IsFixed && Prev->isFixed()) {
17155  if (!EnumUnderlyingTy->isDependentType() &&
17156  !Prev->getIntegerType()->isDependentType() &&
17157  !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17158  Prev->getIntegerType())) {
17159  // TODO: Highlight the underlying type of the redeclaration.
17160  Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17161  << EnumUnderlyingTy << Prev->getIntegerType();
17162  Diag(Prev->getLocation(), diag::note_previous_declaration)
17163  << Prev->getIntegerTypeRange();
17164  return true;
17165  }
17166  } else if (IsFixed != Prev->isFixed()) {
17167  Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17168  << Prev->isFixed();
17169  Diag(Prev->getLocation(), diag::note_previous_declaration);
17170  return true;
17171  }
17172 
17173  return false;
17174 }
17175 
17176 /// Get diagnostic %select index for tag kind for
17177 /// redeclaration diagnostic message.
17178 /// WARNING: Indexes apply to particular diagnostics only!
17179 ///
17180 /// \returns diagnostic %select index.
17182  switch (Tag) {
17183  case TagTypeKind::Struct:
17184  return 0;
17186  return 1;
17187  case TagTypeKind::Class:
17188  return 2;
17189  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17190  }
17191 }
17192 
17193 /// Determine if tag kind is a class-key compatible with
17194 /// class for redeclaration (class, struct, or __interface).
17195 ///
17196 /// \returns true iff the tag kind is compatible.
17198 {
17199  return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17200  Tag == TagTypeKind::Interface;
17201 }
17202 
17204  TagTypeKind TTK) {
17205  if (isa<TypedefDecl>(PrevDecl))
17206  return NTK_Typedef;
17207  else if (isa<TypeAliasDecl>(PrevDecl))
17208  return NTK_TypeAlias;
17209  else if (isa<ClassTemplateDecl>(PrevDecl))
17210  return NTK_Template;
17211  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17212  return NTK_TypeAliasTemplate;
17213  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17214  return NTK_TemplateTemplateArgument;
17215  switch (TTK) {
17216  case TagTypeKind::Struct:
17218  case TagTypeKind::Class:
17219  return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
17220  case TagTypeKind::Union:
17221  return NTK_NonUnion;
17222  case TagTypeKind::Enum:
17223  return NTK_NonEnum;
17224  }
17225  llvm_unreachable("invalid TTK");
17226 }
17227 
17228 /// Determine whether a tag with a given kind is acceptable
17229 /// as a redeclaration of the given tag declaration.
17230 ///
17231 /// \returns true if the new tag kind is acceptable, false otherwise.
17233  TagTypeKind NewTag, bool isDefinition,
17234  SourceLocation NewTagLoc,
17235  const IdentifierInfo *Name) {
17236  // C++ [dcl.type.elab]p3:
17237  // The class-key or enum keyword present in the
17238  // elaborated-type-specifier shall agree in kind with the
17239  // declaration to which the name in the elaborated-type-specifier
17240  // refers. This rule also applies to the form of
17241  // elaborated-type-specifier that declares a class-name or
17242  // friend class since it can be construed as referring to the
17243  // definition of the class. Thus, in any
17244  // elaborated-type-specifier, the enum keyword shall be used to
17245  // refer to an enumeration (7.2), the union class-key shall be
17246  // used to refer to a union (clause 9), and either the class or
17247  // struct class-key shall be used to refer to a class (clause 9)
17248  // declared using the class or struct class-key.
17249  TagTypeKind OldTag = Previous->getTagKind();
17250  if (OldTag != NewTag &&
17251  !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
17252  return false;
17253 
17254  // Tags are compatible, but we might still want to warn on mismatched tags.
17255  // Non-class tags can't be mismatched at this point.
17256  if (!isClassCompatTagKind(NewTag))
17257  return true;
17258 
17259  // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17260  // by our warning analysis. We don't want to warn about mismatches with (eg)
17261  // declarations in system headers that are designed to be specialized, but if
17262  // a user asks us to warn, we should warn if their code contains mismatched
17263  // declarations.
17264  auto IsIgnoredLoc = [&](SourceLocation Loc) {
17265  return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17266  Loc);
17267  };
17268  if (IsIgnoredLoc(NewTagLoc))
17269  return true;
17270 
17271  auto IsIgnored = [&](const TagDecl *Tag) {
17272  return IsIgnoredLoc(Tag->getLocation());
17273  };
17274  while (IsIgnored(Previous)) {
17275  Previous = Previous->getPreviousDecl();
17276  if (!Previous)
17277  return true;
17278  OldTag = Previous->getTagKind();
17279  }
17280 
17281  bool isTemplate = false;
17282  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17283  isTemplate = Record->getDescribedClassTemplate();
17284 
17285  if (inTemplateInstantiation()) {
17286  if (OldTag != NewTag) {
17287  // In a template instantiation, do not offer fix-its for tag mismatches
17288  // since they usually mess up the template instead of fixing the problem.
17289  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17290  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17291  << getRedeclDiagFromTagKind(OldTag);
17292  // FIXME: Note previous location?
17293  }
17294  return true;
17295  }
17296 
17297  if (isDefinition) {
17298  // On definitions, check all previous tags and issue a fix-it for each
17299  // one that doesn't match the current tag.
17300  if (Previous->getDefinition()) {
17301  // Don't suggest fix-its for redefinitions.
17302  return true;
17303  }
17304 
17305  bool previousMismatch = false;
17306  for (const TagDecl *I : Previous->redecls()) {
17307  if (I->getTagKind() != NewTag) {
17308  // Ignore previous declarations for which the warning was disabled.
17309  if (IsIgnored(I))
17310  continue;
17311 
17312  if (!previousMismatch) {
17313  previousMismatch = true;
17314  Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17315  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17316  << getRedeclDiagFromTagKind(I->getTagKind());
17317  }
17318  Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17319  << getRedeclDiagFromTagKind(NewTag)
17320  << FixItHint::CreateReplacement(I->getInnerLocStart(),
17322  }
17323  }
17324  return true;
17325  }
17326 
17327  // Identify the prevailing tag kind: this is the kind of the definition (if
17328  // there is a non-ignored definition), or otherwise the kind of the prior
17329  // (non-ignored) declaration.
17330  const TagDecl *PrevDef = Previous->getDefinition();
17331  if (PrevDef && IsIgnored(PrevDef))
17332  PrevDef = nullptr;
17333  const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17334  if (Redecl->getTagKind() != NewTag) {
17335  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17336  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17337  << getRedeclDiagFromTagKind(OldTag);
17338  Diag(Redecl->getLocation(), diag::note_previous_use);
17339 
17340  // If there is a previous definition, suggest a fix-it.
17341  if (PrevDef) {
17342  Diag(NewTagLoc, diag::note_struct_class_suggestion)
17343  << getRedeclDiagFromTagKind(Redecl->getTagKind())
17346  }
17347  }
17348 
17349  return true;
17350 }
17351 
17352 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17353 /// from an outer enclosing namespace or file scope inside a friend declaration.
17354 /// This should provide the commented out code in the following snippet:
17355 /// namespace N {
17356 /// struct X;
17357 /// namespace M {
17358 /// struct Y { friend struct /*N::*/ X; };
17359 /// }
17360 /// }
17362  SourceLocation NameLoc) {
17363  // While the decl is in a namespace, do repeated lookup of that name and see
17364  // if we get the same namespace back. If we do not, continue until
17365  // translation unit scope, at which point we have a fully qualified NNS.
17368  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17369  // This tag should be declared in a namespace, which can only be enclosed by
17370  // other namespaces. Bail if there's an anonymous namespace in the chain.
17371  NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17372  if (!Namespace || Namespace->isAnonymousNamespace())
17373  return FixItHint();
17374  IdentifierInfo *II = Namespace->getIdentifier();
17375  Namespaces.push_back(II);
17376  NamedDecl *Lookup = SemaRef.LookupSingleName(
17377  S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17378  if (Lookup == Namespace)
17379  break;
17380  }
17381 
17382  // Once we have all the namespaces, reverse them to go outermost first, and
17383  // build an NNS.
17384  SmallString<64> Insertion;
17385  llvm::raw_svector_ostream OS(Insertion);
17386  if (DC->isTranslationUnit())
17387  OS << "::";
17388  std::reverse(Namespaces.begin(), Namespaces.end());
17389  for (auto *II : Namespaces)
17390  OS << II->getName() << "::";
17391  return FixItHint::CreateInsertion(NameLoc, Insertion);
17392 }
17393 
17394 /// Determine whether a tag originally declared in context \p OldDC can
17395 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17396 /// found a declaration in \p OldDC as a previous decl, perhaps through a
17397 /// using-declaration).
17399  DeclContext *NewDC) {
17400  OldDC = OldDC->getRedeclContext();
17401  NewDC = NewDC->getRedeclContext();
17402 
17403  if (OldDC->Equals(NewDC))
17404  return true;
17405 
17406  // In MSVC mode, we allow a redeclaration if the contexts are related (either
17407  // encloses the other).
17408  if (S.getLangOpts().MSVCCompat &&
17409  (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17410  return true;
17411 
17412  return false;
17413 }
17414 
17415 /// This is invoked when we see 'struct foo' or 'struct {'. In the
17416 /// former case, Name will be non-null. In the later case, Name will be null.
17417 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17418 /// reference/declaration/definition of a tag.
17419 ///
17420 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
17421 /// trailing-type-specifier) other than one in an alias-declaration.
17422 ///
17423 /// \param SkipBody If non-null, will be set to indicate if the caller should
17424 /// skip the definition of this tag and treat it as if it were a declaration.
17425 DeclResult
17426 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17427  CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17428  const ParsedAttributesView &Attrs, AccessSpecifier AS,
17429  SourceLocation ModulePrivateLoc,
17430  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17431  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17432  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17433  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17434  OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17435  // If this is not a definition, it must have a name.
17436  IdentifierInfo *OrigName = Name;
17437  assert((Name != nullptr || TUK == TUK_Definition) &&
17438  "Nameless record must be a definition!");
17439  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17440 
17441  OwnedDecl = false;
17443  bool ScopedEnum = ScopedEnumKWLoc.isValid();
17444 
17445  // FIXME: Check member specializations more carefully.
17446  bool isMemberSpecialization = false;
17447  bool Invalid = false;
17448 
17449  // We only need to do this matching if we have template parameters
17450  // or a scope specifier, which also conveniently avoids this work
17451  // for non-C++ cases.
17452  if (TemplateParameterLists.size() > 0 ||
17453  (SS.isNotEmpty() && TUK != TUK_Reference)) {
17454  TemplateParameterList *TemplateParams =
17455  MatchTemplateParametersToScopeSpecifier(
17456  KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17457  TUK == TUK_Friend, isMemberSpecialization, Invalid);
17458 
17459  // C++23 [dcl.type.elab] p2:
17460  // If an elaborated-type-specifier is the sole constituent of a
17461  // declaration, the declaration is ill-formed unless it is an explicit
17462  // specialization, an explicit instantiation or it has one of the
17463  // following forms: [...]
17464  // C++23 [dcl.enum] p1:
17465  // If the enum-head-name of an opaque-enum-declaration contains a
17466  // nested-name-specifier, the declaration shall be an explicit
17467  // specialization.
17468  //
17469  // FIXME: Class template partial specializations can be forward declared
17470  // per CWG2213, but the resolution failed to allow qualified forward
17471  // declarations. This is almost certainly unintentional, so we allow them.
17472  if (TUK == TUK_Declaration && SS.isNotEmpty() && !isMemberSpecialization)
17473  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17475 
17476  if (TemplateParams) {
17477  if (Kind == TagTypeKind::Enum) {
17478  Diag(KWLoc, diag::err_enum_template);
17479  return true;
17480  }
17481 
17482  if (TemplateParams->size() > 0) {
17483  // This is a declaration or definition of a class template (which may
17484  // be a member of another template).
17485 
17486  if (Invalid)
17487  return true;
17488 
17489  OwnedDecl = false;
17490  DeclResult Result = CheckClassTemplate(
17491  S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17492  AS, ModulePrivateLoc,
17493  /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17494  TemplateParameterLists.data(), SkipBody);
17495  return Result.get();
17496  } else {
17497  // The "template<>" header is extraneous.
17498  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17500  isMemberSpecialization = true;
17501  }
17502  }
17503 
17504  if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17505  CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17506  return true;
17507  }
17508 
17509  if (TUK == TUK_Friend && Kind == TagTypeKind::Enum) {
17510  // C++23 [dcl.type.elab]p4:
17511  // If an elaborated-type-specifier appears with the friend specifier as
17512  // an entire member-declaration, the member-declaration shall have one
17513  // of the following forms:
17514  // friend class-key nested-name-specifier(opt) identifier ;
17515  // friend class-key simple-template-id ;
17516  // friend class-key nested-name-specifier template(opt)
17517  // simple-template-id ;
17518  //
17519  // Since enum is not a class-key, so declarations like "friend enum E;"
17520  // are ill-formed. Although CWG2363 reaffirms that such declarations are
17521  // invalid, most implementations accept so we issue a pedantic warning.
17522  Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17523  ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17524  assert(ScopedEnum || !ScopedEnumUsesClassTag);
17525  Diag(KWLoc, diag::note_enum_friend)
17526  << (ScopedEnum + ScopedEnumUsesClassTag);
17527  }
17528 
17529  // Figure out the underlying type if this a enum declaration. We need to do
17530  // this early, because it's needed to detect if this is an incompatible
17531  // redeclaration.
17532  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17533  bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17534 
17535  if (Kind == TagTypeKind::Enum) {
17536  if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17537  // No underlying type explicitly specified, or we failed to parse the
17538  // type, default to int.
17539  EnumUnderlying = Context.IntTy.getTypePtr();
17540  } else if (UnderlyingType.get()) {
17541  // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17542  // integral type; any cv-qualification is ignored.
17543  TypeSourceInfo *TI = nullptr;
17544  GetTypeFromParser(UnderlyingType.get(), &TI);
17545  EnumUnderlying = TI;
17546 
17547  if (CheckEnumUnderlyingType(TI))
17548  // Recover by falling back to int.
17549  EnumUnderlying = Context.IntTy.getTypePtr();
17550 
17551  if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17552  UPPC_FixedUnderlyingType))
17553  EnumUnderlying = Context.IntTy.getTypePtr();
17554 
17555  } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17556  // For MSVC ABI compatibility, unfixed enums must use an underlying type
17557  // of 'int'. However, if this is an unfixed forward declaration, don't set
17558  // the underlying type unless the user enables -fms-compatibility. This
17559  // makes unfixed forward declared enums incomplete and is more conforming.
17560  if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17561  EnumUnderlying = Context.IntTy.getTypePtr();
17562  }
17563  }
17564 
17565  DeclContext *SearchDC = CurContext;
17566  DeclContext *DC = CurContext;
17567  bool isStdBadAlloc = false;
17568  bool isStdAlignValT = false;
17569 
17570  RedeclarationKind Redecl = forRedeclarationInCurContext();
17571  if (TUK == TUK_Friend || TUK == TUK_Reference)
17573 
17574  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17575  /// implemented asks for structural equivalence checking, the returned decl
17576  /// here is passed back to the parser, allowing the tag body to be parsed.
17577  auto createTagFromNewDecl = [&]() -> TagDecl * {
17578  assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17579  // If there is an identifier, use the location of the identifier as the
17580  // location of the decl, otherwise use the location of the struct/union
17581  // keyword.
17582  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17583  TagDecl *New = nullptr;
17584 
17585  if (Kind == TagTypeKind::Enum) {
17586  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17587  ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17588  // If this is an undefined enum, bail.
17589  if (TUK != TUK_Definition && !Invalid)
17590  return nullptr;
17591  if (EnumUnderlying) {
17592  EnumDecl *ED = cast<EnumDecl>(New);
17593  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17594  ED->setIntegerTypeSourceInfo(TI);
17595  else
17596  ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17597  QualType EnumTy = ED->getIntegerType();
17598  ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17599  ? Context.getPromotedIntegerType(EnumTy)
17600  : EnumTy);
17601  }
17602  } else { // struct/union
17603  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17604  nullptr);
17605  }
17606 
17607  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17608  // Add alignment attributes if necessary; these attributes are checked
17609  // when the ASTContext lays out the structure.
17610  //
17611  // It is important for implementing the correct semantics that this
17612  // happen here (in ActOnTag). The #pragma pack stack is
17613  // maintained as a result of parser callbacks which can occur at
17614  // many points during the parsing of a struct declaration (because
17615  // the #pragma tokens are effectively skipped over during the
17616  // parsing of the struct).
17617  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17618  AddAlignmentAttributesForRecord(RD);
17619  AddMsStructLayoutForRecord(RD);
17620  }
17621  }
17622  New->setLexicalDeclContext(CurContext);
17623  return New;
17624  };
17625 
17626  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17627  if (Name && SS.isNotEmpty()) {
17628  // We have a nested-name tag ('struct foo::bar').
17629 
17630  // Check for invalid 'foo::'.
17631  if (SS.isInvalid()) {
17632  Name = nullptr;
17633  goto CreateNewDecl;
17634  }
17635 
17636  // If this is a friend or a reference to a class in a dependent
17637  // context, don't try to make a decl for it.
17638  if (TUK == TUK_Friend || TUK == TUK_Reference) {
17639  DC = computeDeclContext(SS, false);
17640  if (!DC) {
17641  IsDependent = true;
17642  return true;
17643  }
17644  } else {
17645  DC = computeDeclContext(SS, true);
17646  if (!DC) {
17647  Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17648  << SS.getRange();
17649  return true;
17650  }
17651  }
17652 
17653  if (RequireCompleteDeclContext(SS, DC))
17654  return true;
17655 
17656  SearchDC = DC;
17657  // Look-up name inside 'foo::'.
17658  LookupQualifiedName(Previous, DC);
17659 
17660  if (Previous.isAmbiguous())
17661  return true;
17662 
17663  if (Previous.empty()) {
17664  // Name lookup did not find anything. However, if the
17665  // nested-name-specifier refers to the current instantiation,
17666  // and that current instantiation has any dependent base
17667  // classes, we might find something at instantiation time: treat
17668  // this as a dependent elaborated-type-specifier.
17669  // But this only makes any sense for reference-like lookups.
17670  if (Previous.wasNotFoundInCurrentInstantiation() &&
17671  (TUK == TUK_Reference || TUK == TUK_Friend)) {
17672  IsDependent = true;
17673  return true;
17674  }
17675 
17676  // A tag 'foo::bar' must already exist.
17677  Diag(NameLoc, diag::err_not_tag_in_scope)
17678  << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17679  Name = nullptr;
17680  Invalid = true;
17681  goto CreateNewDecl;
17682  }
17683  } else if (Name) {
17684  // C++14 [class.mem]p14:
17685  // If T is the name of a class, then each of the following shall have a
17686  // name different from T:
17687  // -- every member of class T that is itself a type
17688  if (TUK != TUK_Reference && TUK != TUK_Friend &&
17689  DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17690  return true;
17691 
17692  // If this is a named struct, check to see if there was a previous forward
17693  // declaration or definition.
17694  // FIXME: We're looking into outer scopes here, even when we
17695  // shouldn't be. Doing so can result in ambiguities that we
17696  // shouldn't be diagnosing.
17697  LookupName(Previous, S);
17698 
17699  // When declaring or defining a tag, ignore ambiguities introduced
17700  // by types using'ed into this scope.
17701  if (Previous.isAmbiguous() &&
17702  (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17703  LookupResult::Filter F = Previous.makeFilter();
17704  while (F.hasNext()) {
17705  NamedDecl *ND = F.next();
17706  if (!ND->getDeclContext()->getRedeclContext()->Equals(
17707  SearchDC->getRedeclContext()))
17708  F.erase();
17709  }
17710  F.done();
17711  }
17712 
17713  // C++11 [namespace.memdef]p3:
17714  // If the name in a friend declaration is neither qualified nor
17715  // a template-id and the declaration is a function or an
17716  // elaborated-type-specifier, the lookup to determine whether
17717  // the entity has been previously declared shall not consider
17718  // any scopes outside the innermost enclosing namespace.
17719  //
17720  // MSVC doesn't implement the above rule for types, so a friend tag
17721  // declaration may be a redeclaration of a type declared in an enclosing
17722  // scope. They do implement this rule for friend functions.
17723  //
17724  // Does it matter that this should be by scope instead of by
17725  // semantic context?
17726  if (!Previous.empty() && TUK == TUK_Friend) {
17727  DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17728  LookupResult::Filter F = Previous.makeFilter();
17729  bool FriendSawTagOutsideEnclosingNamespace = false;
17730  while (F.hasNext()) {
17731  NamedDecl *ND = F.next();
17733  if (DC->isFileContext() &&
17734  !EnclosingNS->Encloses(ND->getDeclContext())) {
17735  if (getLangOpts().MSVCCompat)
17736  FriendSawTagOutsideEnclosingNamespace = true;
17737  else
17738  F.erase();
17739  }
17740  }
17741  F.done();
17742 
17743  // Diagnose this MSVC extension in the easy case where lookup would have
17744  // unambiguously found something outside the enclosing namespace.
17745  if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17746  NamedDecl *ND = Previous.getFoundDecl();
17747  Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17748  << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17749  }
17750  }
17751 
17752  // Note: there used to be some attempt at recovery here.
17753  if (Previous.isAmbiguous())
17754  return true;
17755 
17756  if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17757  // FIXME: This makes sure that we ignore the contexts associated
17758  // with C structs, unions, and enums when looking for a matching
17759  // tag declaration or definition. See the similar lookup tweak
17760  // in Sema::LookupName; is there a better way to deal with this?
17761  while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17762  SearchDC = SearchDC->getParent();
17763  } else if (getLangOpts().CPlusPlus) {
17764  // Inside ObjCContainer want to keep it as a lexical decl context but go
17765  // past it (most often to TranslationUnit) to find the semantic decl
17766  // context.
17767  while (isa<ObjCContainerDecl>(SearchDC))
17768  SearchDC = SearchDC->getParent();
17769  }
17770  } else if (getLangOpts().CPlusPlus) {
17771  // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17772  // TagDecl the same way as we skip it for named TagDecl.
17773  while (isa<ObjCContainerDecl>(SearchDC))
17774  SearchDC = SearchDC->getParent();
17775  }
17776 
17777  if (Previous.isSingleResult() &&
17778  Previous.getFoundDecl()->isTemplateParameter()) {
17779  // Maybe we will complain about the shadowed template parameter.
17780  DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17781  // Just pretend that we didn't see the previous declaration.
17782  Previous.clear();
17783  }
17784 
17785  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17786  DC->Equals(getStdNamespace())) {
17787  if (Name->isStr("bad_alloc")) {
17788  // This is a declaration of or a reference to "std::bad_alloc".
17789  isStdBadAlloc = true;
17790 
17791  // If std::bad_alloc has been implicitly declared (but made invisible to
17792  // name lookup), fill in this implicit declaration as the previous
17793  // declaration, so that the declarations get chained appropriately.
17794  if (Previous.empty() && StdBadAlloc)
17795  Previous.addDecl(getStdBadAlloc());
17796  } else if (Name->isStr("align_val_t")) {
17797  isStdAlignValT = true;
17798  if (Previous.empty() && StdAlignValT)
17799  Previous.addDecl(getStdAlignValT());
17800  }
17801  }
17802 
17803  // If we didn't find a previous declaration, and this is a reference
17804  // (or friend reference), move to the correct scope. In C++, we
17805  // also need to do a redeclaration lookup there, just in case
17806  // there's a shadow friend decl.
17807  if (Name && Previous.empty() &&
17808  (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17809  if (Invalid) goto CreateNewDecl;
17810  assert(SS.isEmpty());
17811 
17812  if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17813  // C++ [basic.scope.pdecl]p5:
17814  // -- for an elaborated-type-specifier of the form
17815  //
17816  // class-key identifier
17817  //
17818  // if the elaborated-type-specifier is used in the
17819  // decl-specifier-seq or parameter-declaration-clause of a
17820  // function defined in namespace scope, the identifier is
17821  // declared as a class-name in the namespace that contains
17822  // the declaration; otherwise, except as a friend
17823  // declaration, the identifier is declared in the smallest
17824  // non-class, non-function-prototype scope that contains the
17825  // declaration.
17826  //
17827  // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17828  // C structs and unions.
17829  //
17830  // It is an error in C++ to declare (rather than define) an enum
17831  // type, including via an elaborated type specifier. We'll
17832  // diagnose that later; for now, declare the enum in the same
17833  // scope as we would have picked for any other tag type.
17834  //
17835  // GNU C also supports this behavior as part of its incomplete
17836  // enum types extension, while GNU C++ does not.
17837  //
17838  // Find the context where we'll be declaring the tag.
17839  // FIXME: We would like to maintain the current DeclContext as the
17840  // lexical context,
17841  SearchDC = getTagInjectionContext(SearchDC);
17842 
17843  // Find the scope where we'll be declaring the tag.
17844  S = getTagInjectionScope(S, getLangOpts());
17845  } else {
17846  assert(TUK == TUK_Friend);
17847  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17848 
17849  // C++ [namespace.memdef]p3:
17850  // If a friend declaration in a non-local class first declares a
17851  // class or function, the friend class or function is a member of
17852  // the innermost enclosing namespace.
17853  SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17854  : SearchDC->getEnclosingNamespaceContext();
17855  }
17856 
17857  // In C++, we need to do a redeclaration lookup to properly
17858  // diagnose some problems.
17859  // FIXME: redeclaration lookup is also used (with and without C++) to find a
17860  // hidden declaration so that we don't get ambiguity errors when using a
17861  // type declared by an elaborated-type-specifier. In C that is not correct
17862  // and we should instead merge compatible types found by lookup.
17863  if (getLangOpts().CPlusPlus) {
17864  // FIXME: This can perform qualified lookups into function contexts,
17865  // which are meaningless.
17866  Previous.setRedeclarationKind(forRedeclarationInCurContext());
17867  LookupQualifiedName(Previous, SearchDC);
17868  } else {
17869  Previous.setRedeclarationKind(forRedeclarationInCurContext());
17870  LookupName(Previous, S);
17871  }
17872  }
17873 
17874  // If we have a known previous declaration to use, then use it.
17875  if (Previous.empty() && SkipBody && SkipBody->Previous)
17876  Previous.addDecl(SkipBody->Previous);
17877 
17878  if (!Previous.empty()) {
17879  NamedDecl *PrevDecl = Previous.getFoundDecl();
17880  NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17881 
17882  // It's okay to have a tag decl in the same scope as a typedef
17883  // which hides a tag decl in the same scope. Finding this
17884  // with a redeclaration lookup can only actually happen in C++.
17885  //
17886  // This is also okay for elaborated-type-specifiers, which is
17887  // technically forbidden by the current standard but which is
17888  // okay according to the likely resolution of an open issue;
17889  // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17890  if (getLangOpts().CPlusPlus) {
17891  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17892  if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17893  TagDecl *Tag = TT->getDecl();
17894  if (Tag->getDeclName() == Name &&
17896  ->Equals(TD->getDeclContext()->getRedeclContext())) {
17897  PrevDecl = Tag;
17898  Previous.clear();
17899  Previous.addDecl(Tag);
17900  Previous.resolveKind();
17901  }
17902  }
17903  }
17904  }
17905 
17906  // If this is a redeclaration of a using shadow declaration, it must
17907  // declare a tag in the same context. In MSVC mode, we allow a
17908  // redefinition if either context is within the other.
17909  if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17910  auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17911  if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17912  isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17913  !(OldTag && isAcceptableTagRedeclContext(
17914  *this, OldTag->getDeclContext(), SearchDC))) {
17915  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17916  Diag(Shadow->getTargetDecl()->getLocation(),
17917  diag::note_using_decl_target);
17918  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17919  << 0;
17920  // Recover by ignoring the old declaration.
17921  Previous.clear();
17922  goto CreateNewDecl;
17923  }
17924  }
17925 
17926  if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17927  // If this is a use of a previous tag, or if the tag is already declared
17928  // in the same scope (so that the definition/declaration completes or
17929  // rementions the tag), reuse the decl.
17930  if (TUK == TUK_Reference || TUK == TUK_Friend ||
17931  isDeclInScope(DirectPrevDecl, SearchDC, S,
17932  SS.isNotEmpty() || isMemberSpecialization)) {
17933  // Make sure that this wasn't declared as an enum and now used as a
17934  // struct or something similar.
17935  if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17936  TUK == TUK_Definition, KWLoc,
17937  Name)) {
17938  bool SafeToContinue =
17939  (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17940  Kind != TagTypeKind::Enum);
17941  if (SafeToContinue)
17942  Diag(KWLoc, diag::err_use_with_wrong_tag)
17943  << Name
17945  PrevTagDecl->getKindName());
17946  else
17947  Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17948  Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17949 
17950  if (SafeToContinue)
17951  Kind = PrevTagDecl->getTagKind();
17952  else {
17953  // Recover by making this an anonymous redefinition.
17954  Name = nullptr;
17955  Previous.clear();
17956  Invalid = true;
17957  }
17958  }
17959 
17960  if (Kind == TagTypeKind::Enum &&
17961  PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17962  const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17963  if (TUK == TUK_Reference || TUK == TUK_Friend)
17964  return PrevTagDecl;
17965 
17966  QualType EnumUnderlyingTy;
17967  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17968  EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17969  else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17970  EnumUnderlyingTy = QualType(T, 0);
17971 
17972  // All conflicts with previous declarations are recovered by
17973  // returning the previous declaration, unless this is a definition,
17974  // in which case we want the caller to bail out.
17975  if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17976  ScopedEnum, EnumUnderlyingTy,
17977  IsFixed, PrevEnum))
17978  return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17979  }
17980 
17981  // C++11 [class.mem]p1:
17982  // A member shall not be declared twice in the member-specification,
17983  // except that a nested class or member class template can be declared
17984  // and then later defined.
17985  if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17986  S->isDeclScope(PrevDecl)) {
17987  Diag(NameLoc, diag::ext_member_redeclared);
17988  Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17989  }
17990 
17991  if (!Invalid) {
17992  // If this is a use, just return the declaration we found, unless
17993  // we have attributes.
17994  if (TUK == TUK_Reference || TUK == TUK_Friend) {
17995  if (!Attrs.empty()) {
17996  // FIXME: Diagnose these attributes. For now, we create a new
17997  // declaration to hold them.
17998  } else if (TUK == TUK_Reference &&
17999  (PrevTagDecl->getFriendObjectKind() ==
18001  PrevDecl->getOwningModule() != getCurrentModule()) &&
18002  SS.isEmpty()) {
18003  // This declaration is a reference to an existing entity, but
18004  // has different visibility from that entity: it either makes
18005  // a friend visible or it makes a type visible in a new module.
18006  // In either case, create a new declaration. We only do this if
18007  // the declaration would have meant the same thing if no prior
18008  // declaration were found, that is, if it was found in the same
18009  // scope where we would have injected a declaration.
18010  if (!getTagInjectionContext(CurContext)->getRedeclContext()
18011  ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18012  return PrevTagDecl;
18013  // This is in the injected scope, create a new declaration in
18014  // that scope.
18015  S = getTagInjectionScope(S, getLangOpts());
18016  } else {
18017  return PrevTagDecl;
18018  }
18019  }
18020 
18021  // Diagnose attempts to redefine a tag.
18022  if (TUK == TUK_Definition) {
18023  if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
18024  // If we're defining a specialization and the previous definition
18025  // is from an implicit instantiation, don't emit an error
18026  // here; we'll catch this in the general case below.
18027  bool IsExplicitSpecializationAfterInstantiation = false;
18028  if (isMemberSpecialization) {
18029  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18030  IsExplicitSpecializationAfterInstantiation =
18031  RD->getTemplateSpecializationKind() !=
18033  else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18034  IsExplicitSpecializationAfterInstantiation =
18035  ED->getTemplateSpecializationKind() !=
18037  }
18038 
18039  // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
18040  // not keep more that one definition around (merge them). However,
18041  // ensure the decl passes the structural compatibility check in
18042  // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18043  NamedDecl *Hidden = nullptr;
18044  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
18045  // There is a definition of this tag, but it is not visible. We
18046  // explicitly make use of C++'s one definition rule here, and
18047  // assume that this definition is identical to the hidden one
18048  // we already have. Make the existing definition visible and
18049  // use it in place of this one.
18050  if (!getLangOpts().CPlusPlus) {
18051  // Postpone making the old definition visible until after we
18052  // complete parsing the new one and do the structural
18053  // comparison.
18054  SkipBody->CheckSameAsPrevious = true;
18055  SkipBody->New = createTagFromNewDecl();
18056  SkipBody->Previous = Def;
18057  return Def;
18058  } else {
18059  SkipBody->ShouldSkip = true;
18060  SkipBody->Previous = Def;
18061  makeMergedDefinitionVisible(Hidden);
18062  // Carry on and handle it like a normal definition. We'll
18063  // skip starting the definitiion later.
18064  }
18065  } else if (!IsExplicitSpecializationAfterInstantiation) {
18066  // A redeclaration in function prototype scope in C isn't
18067  // visible elsewhere, so merely issue a warning.
18068  if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
18069  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
18070  else
18071  Diag(NameLoc, diag::err_redefinition) << Name;
18072  notePreviousDefinition(Def,
18073  NameLoc.isValid() ? NameLoc : KWLoc);
18074  // If this is a redefinition, recover by making this
18075  // struct be anonymous, which will make any later
18076  // references get the previous definition.
18077  Name = nullptr;
18078  Previous.clear();
18079  Invalid = true;
18080  }
18081  } else {
18082  // If the type is currently being defined, complain
18083  // about a nested redefinition.
18084  auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
18085  if (TD->isBeingDefined()) {
18086  Diag(NameLoc, diag::err_nested_redefinition) << Name;
18087  Diag(PrevTagDecl->getLocation(),
18088  diag::note_previous_definition);
18089  Name = nullptr;
18090  Previous.clear();
18091  Invalid = true;
18092  }
18093  }
18094 
18095  // Okay, this is definition of a previously declared or referenced
18096  // tag. We're going to create a new Decl for it.
18097  }
18098 
18099  // Okay, we're going to make a redeclaration. If this is some kind
18100  // of reference, make sure we build the redeclaration in the same DC
18101  // as the original, and ignore the current access specifier.
18102  if (TUK == TUK_Friend || TUK == TUK_Reference) {
18103  SearchDC = PrevTagDecl->getDeclContext();
18104  AS = AS_none;
18105  }
18106  }
18107  // If we get here we have (another) forward declaration or we
18108  // have a definition. Just create a new decl.
18109 
18110  } else {
18111  // If we get here, this is a definition of a new tag type in a nested
18112  // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18113  // new decl/type. We set PrevDecl to NULL so that the entities
18114  // have distinct types.
18115  Previous.clear();
18116  }
18117  // If we get here, we're going to create a new Decl. If PrevDecl
18118  // is non-NULL, it's a definition of the tag declared by
18119  // PrevDecl. If it's NULL, we have a new definition.
18120 
18121  // Otherwise, PrevDecl is not a tag, but was found with tag
18122  // lookup. This is only actually possible in C++, where a few
18123  // things like templates still live in the tag namespace.
18124  } else {
18125  // Use a better diagnostic if an elaborated-type-specifier
18126  // found the wrong kind of type on the first
18127  // (non-redeclaration) lookup.
18128  if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
18129  !Previous.isForRedeclaration()) {
18130  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18131  Diag(NameLoc, diag::err_tag_reference_non_tag)
18132  << PrevDecl << NTK << llvm::to_underlying(Kind);
18133  Diag(PrevDecl->getLocation(), diag::note_declared_at);
18134  Invalid = true;
18135 
18136  // Otherwise, only diagnose if the declaration is in scope.
18137  } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18138  SS.isNotEmpty() || isMemberSpecialization)) {
18139  // do nothing
18140 
18141  // Diagnose implicit declarations introduced by elaborated types.
18142  } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
18143  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18144  Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18145  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18146  Invalid = true;
18147 
18148  // Otherwise it's a declaration. Call out a particularly common
18149  // case here.
18150  } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18151  unsigned Kind = 0;
18152  if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18153  Diag(NameLoc, diag::err_tag_definition_of_typedef)
18154  << Name << Kind << TND->getUnderlyingType();
18155  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18156  Invalid = true;
18157 
18158  // Otherwise, diagnose.
18159  } else {
18160  // The tag name clashes with something else in the target scope,
18161  // issue an error and recover by making this tag be anonymous.
18162  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18163  notePreviousDefinition(PrevDecl, NameLoc);
18164  Name = nullptr;
18165  Invalid = true;
18166  }
18167 
18168  // The existing declaration isn't relevant to us; we're in a
18169  // new scope, so clear out the previous declaration.
18170  Previous.clear();
18171  }
18172  }
18173 
18174 CreateNewDecl:
18175 
18176  TagDecl *PrevDecl = nullptr;
18177  if (Previous.isSingleResult())
18178  PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18179 
18180  // If there is an identifier, use the location of the identifier as the
18181  // location of the decl, otherwise use the location of the struct/union
18182  // keyword.
18183  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18184 
18185  // Otherwise, create a new declaration. If there is a previous
18186  // declaration of the same entity, the two will be linked via
18187  // PrevDecl.
18188  TagDecl *New;
18189 
18190  if (Kind == TagTypeKind::Enum) {
18191  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18192  // enum X { A, B, C } D; D should chain to X.
18193  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18194  cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18195  ScopedEnumUsesClassTag, IsFixed);
18196 
18197  if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18198  StdAlignValT = cast<EnumDecl>(New);
18199 
18200  // If this is an undefined enum, warn.
18201  if (TUK != TUK_Definition && !Invalid) {
18202  TagDecl *Def;
18203  if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18204  // C++0x: 7.2p2: opaque-enum-declaration.
18205  // Conflicts are diagnosed above. Do nothing.
18206  }
18207  else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18208  Diag(Loc, diag::ext_forward_ref_enum_def)
18209  << New;
18210  Diag(Def->getLocation(), diag::note_previous_definition);
18211  } else {
18212  unsigned DiagID = diag::ext_forward_ref_enum;
18213  if (getLangOpts().MSVCCompat)
18214  DiagID = diag::ext_ms_forward_ref_enum;
18215  else if (getLangOpts().CPlusPlus)
18216  DiagID = diag::err_forward_ref_enum;
18217  Diag(Loc, DiagID);
18218  }
18219  }
18220 
18221  if (EnumUnderlying) {
18222  EnumDecl *ED = cast<EnumDecl>(New);
18223  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
18224  ED->setIntegerTypeSourceInfo(TI);
18225  else
18226  ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
18227  QualType EnumTy = ED->getIntegerType();
18228  ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18229  ? Context.getPromotedIntegerType(EnumTy)
18230  : EnumTy);
18231  assert(ED->isComplete() && "enum with type should be complete");
18232  }
18233  } else {
18234  // struct/union/class
18235 
18236  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18237  // struct X { int A; } D; D should chain to X.
18238  if (getLangOpts().CPlusPlus) {
18239  // FIXME: Look for a way to use RecordDecl for simple structs.
18240  New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18241  cast_or_null<CXXRecordDecl>(PrevDecl));
18242 
18243  if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18244  StdBadAlloc = cast<CXXRecordDecl>(New);
18245  } else
18246  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18247  cast_or_null<RecordDecl>(PrevDecl));
18248  }
18249 
18250  // Only C23 and later allow defining new types in 'offsetof()'.
18251  if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus &&
18252  !getLangOpts().C23)
18253  Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18254  << (OOK == OOK_Macro) << New->getSourceRange();
18255 
18256  // C++11 [dcl.type]p3:
18257  // A type-specifier-seq shall not define a class or enumeration [...].
18258  if (!Invalid && getLangOpts().CPlusPlus &&
18259  (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
18260  Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18261  << Context.getTagDeclType(New);
18262  Invalid = true;
18263  }
18264 
18265  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
18266  DC->getDeclKind() == Decl::Enum) {
18267  Diag(New->getLocation(), diag::err_type_defined_in_enum)
18268  << Context.getTagDeclType(New);
18269  Invalid = true;
18270  }
18271 
18272  // Maybe add qualifier info.
18273  if (SS.isNotEmpty()) {
18274  if (SS.isSet()) {
18275  // If this is either a declaration or a definition, check the
18276  // nested-name-specifier against the current context.
18277  if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
18278  diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18279  /*TemplateId=*/nullptr,
18280  isMemberSpecialization))
18281  Invalid = true;
18282 
18283  New->setQualifierInfo(SS.getWithLocInContext(Context));
18284  if (TemplateParameterLists.size() > 0) {
18285  New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18286  }
18287  }
18288  else
18289  Invalid = true;
18290  }
18291 
18292  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18293  // Add alignment attributes if necessary; these attributes are checked when
18294  // the ASTContext lays out the structure.
18295  //
18296  // It is important for implementing the correct semantics that this
18297  // happen here (in ActOnTag). The #pragma pack stack is
18298  // maintained as a result of parser callbacks which can occur at
18299  // many points during the parsing of a struct declaration (because
18300  // the #pragma tokens are effectively skipped over during the
18301  // parsing of the struct).
18302  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18303  AddAlignmentAttributesForRecord(RD);
18304  AddMsStructLayoutForRecord(RD);
18305  }
18306  }
18307 
18308  if (ModulePrivateLoc.isValid()) {
18309  if (isMemberSpecialization)
18310  Diag(New->getLocation(), diag::err_module_private_specialization)
18311  << 2
18312  << FixItHint::CreateRemoval(ModulePrivateLoc);
18313  // __module_private__ does not apply to local classes. However, we only
18314  // diagnose this as an error when the declaration specifiers are
18315  // freestanding. Here, we just ignore the __module_private__.
18316  else if (!SearchDC->isFunctionOrMethod())
18317  New->setModulePrivate();
18318  }
18319 
18320  // If this is a specialization of a member class (of a class template),
18321  // check the specialization.
18322  if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18323  Invalid = true;
18324 
18325  // If we're declaring or defining a tag in function prototype scope in C,
18326  // note that this type can only be used within the function and add it to
18327  // the list of decls to inject into the function definition scope.
18328  if ((Name || Kind == TagTypeKind::Enum) &&
18329  getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18330  if (getLangOpts().CPlusPlus) {
18331  // C++ [dcl.fct]p6:
18332  // Types shall not be defined in return or parameter types.
18333  if (TUK == TUK_Definition && !IsTypeSpecifier) {
18334  Diag(Loc, diag::err_type_defined_in_param_type)
18335  << Name;
18336  Invalid = true;
18337  }
18338  } else if (!PrevDecl) {
18339  Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18340  }
18341  }
18342 
18343  if (Invalid)
18344  New->setInvalidDecl();
18345 
18346  // Set the lexical context. If the tag has a C++ scope specifier, the
18347  // lexical context will be different from the semantic context.
18348  New->setLexicalDeclContext(CurContext);
18349 
18350  // Mark this as a friend decl if applicable.
18351  // In Microsoft mode, a friend declaration also acts as a forward
18352  // declaration so we always pass true to setObjectOfFriendDecl to make
18353  // the tag name visible.
18354  if (TUK == TUK_Friend)
18355  New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18356 
18357  // Set the access specifier.
18358  if (!Invalid && SearchDC->isRecord())
18359  SetMemberAccessSpecifier(New, PrevDecl, AS);
18360 
18361  if (PrevDecl)
18362  CheckRedeclarationInModule(New, PrevDecl);
18363 
18364  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18365  New->startDefinition();
18366 
18367  ProcessDeclAttributeList(S, New, Attrs);
18368  AddPragmaAttributes(S, New);
18369 
18370  // If this has an identifier, add it to the scope stack.
18371  if (TUK == TUK_Friend) {
18372  // We might be replacing an existing declaration in the lookup tables;
18373  // if so, borrow its access specifier.
18374  if (PrevDecl)
18375  New->setAccess(PrevDecl->getAccess());
18376 
18378  DC->makeDeclVisibleInContext(New);
18379  if (Name) // can be null along some error paths
18380  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18381  PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18382  } else if (Name) {
18383  S = getNonFieldDeclScope(S);
18384  PushOnScopeChains(New, S, true);
18385  } else {
18386  CurContext->addDecl(New);
18387  }
18388 
18389  // If this is the C FILE type, notify the AST context.
18390  if (IdentifierInfo *II = New->getIdentifier())
18391  if (!New->isInvalidDecl() &&
18393  II->isStr("FILE"))
18394  Context.setFILEDecl(New);
18395 
18396  if (PrevDecl)
18397  mergeDeclAttributes(New, PrevDecl);
18398 
18399  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18400  inferGslOwnerPointerAttribute(CXXRD);
18401  inferNullableClassAttribute(CXXRD);
18402  }
18403 
18404  // If there's a #pragma GCC visibility in scope, set the visibility of this
18405  // record.
18406  AddPushedVisibilityAttribute(New);
18407 
18408  if (isMemberSpecialization && !New->isInvalidDecl())
18409  CompleteMemberSpecialization(New, Previous);
18410 
18411  OwnedDecl = true;
18412  // In C++, don't return an invalid declaration. We can't recover well from
18413  // the cases where we make the type anonymous.
18414  if (Invalid && getLangOpts().CPlusPlus) {
18415  if (New->isBeingDefined())
18416  if (auto RD = dyn_cast<RecordDecl>(New))
18417  RD->completeDefinition();
18418  return true;
18419  } else if (SkipBody && SkipBody->ShouldSkip) {
18420  return SkipBody->Previous;
18421  } else {
18422  return New;
18423  }
18424 }
18425 
18427  AdjustDeclIfTemplate(TagD);
18428  TagDecl *Tag = cast<TagDecl>(TagD);
18429 
18430  // Enter the tag context.
18431  PushDeclContext(S, Tag);
18432 
18433  ActOnDocumentableDecl(TagD);
18434 
18435  // If there's a #pragma GCC visibility in scope, set the visibility of this
18436  // record.
18437  AddPushedVisibilityAttribute(Tag);
18438 }
18439 
18441  if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18442  return false;
18443 
18444  // Make the previous decl visible.
18445  makeMergedDefinitionVisible(SkipBody.Previous);
18446  return true;
18447 }
18448 
18450  assert(IDecl->getLexicalParent() == CurContext &&
18451  "The next DeclContext should be lexically contained in the current one.");
18452  CurContext = IDecl;
18453 }
18454 
18456  SourceLocation FinalLoc,
18457  bool IsFinalSpelledSealed,
18458  bool IsAbstract,
18459  SourceLocation LBraceLoc) {
18460  AdjustDeclIfTemplate(TagD);
18461  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18462 
18463  FieldCollector->StartClass();
18464 
18465  if (!Record->getIdentifier())
18466  return;
18467 
18468  if (IsAbstract)
18469  Record->markAbstract();
18470 
18471  if (FinalLoc.isValid()) {
18472  Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18473  IsFinalSpelledSealed
18474  ? FinalAttr::Keyword_sealed
18475  : FinalAttr::Keyword_final));
18476  }
18477  // C++ [class]p2:
18478  // [...] The class-name is also inserted into the scope of the
18479  // class itself; this is known as the injected-class-name. For
18480  // purposes of access checking, the injected-class-name is treated
18481  // as if it were a public member name.
18482  CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18483  Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18484  Record->getLocation(), Record->getIdentifier(),
18485  /*PrevDecl=*/nullptr,
18486  /*DelayTypeCreation=*/true);
18487  Context.getTypeDeclType(InjectedClassName, Record);
18488  InjectedClassName->setImplicit();
18489  InjectedClassName->setAccess(AS_public);
18490  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18491  InjectedClassName->setDescribedClassTemplate(Template);
18492  PushOnScopeChains(InjectedClassName, S);
18493  assert(InjectedClassName->isInjectedClassName() &&
18494  "Broken injected-class-name");
18495 }
18496 
18498  SourceRange BraceRange) {
18499  AdjustDeclIfTemplate(TagD);
18500  TagDecl *Tag = cast<TagDecl>(TagD);
18501  Tag->setBraceRange(BraceRange);
18502 
18503  // Make sure we "complete" the definition even it is invalid.
18504  if (Tag->isBeingDefined()) {
18505  assert(Tag->isInvalidDecl() && "We should already have completed it");
18506  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18507  RD->completeDefinition();
18508  }
18509 
18510  if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18511  FieldCollector->FinishClass();
18512  if (RD->hasAttr<SYCLSpecialClassAttr>() && getLangOpts().SYCLIsDevice) {
18513  auto *Def = RD->getDefinition();
18514  assert(Def && "The record is expected to have a completed definition");
18515  unsigned NumInitMethods = 0;
18516  for (auto *Method : Def->methods()) {
18517  if (!Method->getIdentifier())
18518  continue;
18519  if (Method->getName() == "__init")
18520  NumInitMethods++;
18521  }
18522  if (NumInitMethods > 1 || !Def->hasInitMethod())
18523  Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18524  }
18525  }
18526 
18527  // Exit this scope of this tag's definition.
18528  PopDeclContext();
18529 
18530  if (getCurLexicalContext()->isObjCContainer() &&
18531  Tag->getDeclContext()->isFileContext())
18533 
18534  // Notify the consumer that we've defined a tag.
18535  if (!Tag->isInvalidDecl())
18536  Consumer.HandleTagDeclDefinition(Tag);
18537 
18538  // Clangs implementation of #pragma align(packed) differs in bitfield layout
18539  // from XLs and instead matches the XL #pragma pack(1) behavior.
18540  if (Context.getTargetInfo().getTriple().isOSAIX() &&
18541  AlignPackStack.hasValue()) {
18542  AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18543  // Only diagnose #pragma align(packed).
18544  if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18545  return;
18546  const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18547  if (!RD)
18548  return;
18549  // Only warn if there is at least 1 bitfield member.
18550  if (llvm::any_of(RD->fields(),
18551  [](const FieldDecl *FD) { return FD->isBitField(); }))
18552  Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18553  }
18554 }
18555 
18557  // Exit this scope of this interface definition.
18558  PopDeclContext();
18559 }
18560 
18562  assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18563  OriginalLexicalContext = ObjCCtx;
18564  ActOnObjCContainerFinishDefinition();
18565 }
18566 
18568  ActOnObjCContainerStartDefinition(ObjCCtx);
18569  OriginalLexicalContext = nullptr;
18570 }
18571 
18573  AdjustDeclIfTemplate(TagD);
18574  TagDecl *Tag = cast<TagDecl>(TagD);
18575  Tag->setInvalidDecl();
18576 
18577  // Make sure we "complete" the definition even it is invalid.
18578  if (Tag->isBeingDefined()) {
18579  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18580  RD->completeDefinition();
18581  }
18582 
18583  // We're undoing ActOnTagStartDefinition here, not
18584  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18585  // the FieldCollector.
18586 
18587  PopDeclContext();
18588 }
18589 
18590 // Note that FieldName may be null for anonymous bitfields.
18592  const IdentifierInfo *FieldName,
18593  QualType FieldTy, bool IsMsStruct,
18594  Expr *BitWidth) {
18595  assert(BitWidth);
18596  if (BitWidth->containsErrors())
18597  return ExprError();
18598 
18599  // C99 6.7.2.1p4 - verify the field type.
18600  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18601  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18602  // Handle incomplete and sizeless types with a specific error.
18603  if (RequireCompleteSizedType(FieldLoc, FieldTy,
18604  diag::err_field_incomplete_or_sizeless))
18605  return ExprError();
18606  if (FieldName)
18607  return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18608  << FieldName << FieldTy << BitWidth->getSourceRange();
18609  return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18610  << FieldTy << BitWidth->getSourceRange();
18611  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18612  UPPC_BitFieldWidth))
18613  return ExprError();
18614 
18615  // If the bit-width is type- or value-dependent, don't try to check
18616  // it now.
18617  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18618  return BitWidth;
18619 
18621  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18622  if (ICE.isInvalid())
18623  return ICE;
18624  BitWidth = ICE.get();
18625 
18626  // Zero-width bitfield is ok for anonymous field.
18627  if (Value == 0 && FieldName)
18628  return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18629  << FieldName << BitWidth->getSourceRange();
18630 
18631  if (Value.isSigned() && Value.isNegative()) {
18632  if (FieldName)
18633  return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18634  << FieldName << toString(Value, 10);
18635  return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18636  << toString(Value, 10);
18637  }
18638 
18639  // The size of the bit-field must not exceed our maximum permitted object
18640  // size.
18641  if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18642  return Diag(FieldLoc, diag::err_bitfield_too_wide)
18643  << !FieldName << FieldName << toString(Value, 10);
18644  }
18645 
18646  if (!FieldTy->isDependentType()) {
18647  uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18648  uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18649  bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18650 
18651  // Over-wide bitfields are an error in C or when using the MSVC bitfield
18652  // ABI.
18653  bool CStdConstraintViolation =
18654  BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18655  bool MSBitfieldViolation =
18656  Value.ugt(TypeStorageSize) &&
18657  (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18658  if (CStdConstraintViolation || MSBitfieldViolation) {
18659  unsigned DiagWidth =
18660  CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18661  return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18662  << (bool)FieldName << FieldName << toString(Value, 10)
18663  << !CStdConstraintViolation << DiagWidth;
18664  }
18665 
18666  // Warn on types where the user might conceivably expect to get all
18667  // specified bits as value bits: that's all integral types other than
18668  // 'bool'.
18669  if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18670  Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18671  << FieldName << toString(Value, 10)
18672  << (unsigned)TypeWidth;
18673  }
18674  }
18675 
18676  return BitWidth;
18677 }
18678 
18679 /// ActOnField - Each field of a C struct/union is passed into this in order
18680 /// to create a FieldDecl object for it.
18682  Declarator &D, Expr *BitfieldWidth) {
18683  FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18684  D, BitfieldWidth,
18685  /*InitStyle=*/ICIS_NoInit, AS_public);
18686  return Res;
18687 }
18688 
18689 /// HandleField - Analyze a field of a C struct or a C++ data member.
18690 ///
18692  SourceLocation DeclStart,
18693  Declarator &D, Expr *BitWidth,
18694  InClassInitStyle InitStyle,
18695  AccessSpecifier AS) {
18696  if (D.isDecompositionDeclarator()) {
18698  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18699  << Decomp.getSourceRange();
18700  return nullptr;
18701  }
18702 
18703  const IdentifierInfo *II = D.getIdentifier();
18704  SourceLocation Loc = DeclStart;
18705  if (II) Loc = D.getIdentifierLoc();
18706 
18707  TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18708  QualType T = TInfo->getType();
18709  if (getLangOpts().CPlusPlus) {
18710  CheckExtraCXXDefaultArguments(D);
18711 
18712  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18713  UPPC_DataMemberType)) {
18714  D.setInvalidType();
18715  T = Context.IntTy;
18716  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18717  }
18718  }
18719 
18720  DiagnoseFunctionSpecifiers(D.getDeclSpec());
18721 
18722  if (D.getDeclSpec().isInlineSpecified())
18723  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18724  << getLangOpts().CPlusPlus17;
18727  diag::err_invalid_thread)
18728  << DeclSpec::getSpecifierName(TSCS);
18729 
18730  // Check to see if this name was declared as a member previously
18731  NamedDecl *PrevDecl = nullptr;
18732  LookupResult Previous(*this, II, Loc, LookupMemberName,
18734  LookupName(Previous, S);
18735  switch (Previous.getResultKind()) {
18736  case LookupResult::Found:
18738  PrevDecl = Previous.getAsSingle<NamedDecl>();
18739  break;
18740 
18742  PrevDecl = Previous.getRepresentativeDecl();
18743  break;
18744 
18748  break;
18749  }
18750  Previous.suppressDiagnostics();
18751 
18752  if (PrevDecl && PrevDecl->isTemplateParameter()) {
18753  // Maybe we will complain about the shadowed template parameter.
18754  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18755  // Just pretend that we didn't see the previous declaration.
18756  PrevDecl = nullptr;
18757  }
18758 
18759  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18760  PrevDecl = nullptr;
18761 
18762  bool Mutable
18764  SourceLocation TSSL = D.getBeginLoc();
18765  FieldDecl *NewFD
18766  = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18767  TSSL, AS, PrevDecl, &D);
18768 
18769  if (NewFD->isInvalidDecl())
18770  Record->setInvalidDecl();
18771 
18773  NewFD->setModulePrivate();
18774 
18775  if (NewFD->isInvalidDecl() && PrevDecl) {
18776  // Don't introduce NewFD into scope; there's already something
18777  // with the same name in the same scope.
18778  } else if (II) {
18779  PushOnScopeChains(NewFD, S);
18780  } else
18781  Record->addDecl(NewFD);
18782 
18783  return NewFD;
18784 }
18785 
18786 /// Build a new FieldDecl and check its well-formedness.
18787 ///
18788 /// This routine builds a new FieldDecl given the fields name, type,
18789 /// record, etc. \p PrevDecl should refer to any previous declaration
18790 /// with the same name and in the same scope as the field to be
18791 /// created.
18792 ///
18793 /// \returns a new FieldDecl.
18794 ///
18795 /// \todo The Declarator argument is a hack. It will be removed once
18797  TypeSourceInfo *TInfo,
18799  bool Mutable, Expr *BitWidth,
18800  InClassInitStyle InitStyle,
18801  SourceLocation TSSL,
18802  AccessSpecifier AS, NamedDecl *PrevDecl,
18803  Declarator *D) {
18804  const IdentifierInfo *II = Name.getAsIdentifierInfo();
18805  bool InvalidDecl = false;
18806  if (D) InvalidDecl = D->isInvalidType();
18807 
18808  // If we receive a broken type, recover by assuming 'int' and
18809  // marking this declaration as invalid.
18810  if (T.isNull() || T->containsErrors()) {
18811  InvalidDecl = true;
18812  T = Context.IntTy;
18813  }
18814 
18815  QualType EltTy = Context.getBaseElementType(T);
18816  if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18817  if (RequireCompleteSizedType(Loc, EltTy,
18818  diag::err_field_incomplete_or_sizeless)) {
18819  // Fields of incomplete type force their record to be invalid.
18820  Record->setInvalidDecl();
18821  InvalidDecl = true;
18822  } else {
18823  NamedDecl *Def;
18824  EltTy->isIncompleteType(&Def);
18825  if (Def && Def->isInvalidDecl()) {
18826  Record->setInvalidDecl();
18827  InvalidDecl = true;
18828  }
18829  }
18830  }
18831 
18832  // TR 18037 does not allow fields to be declared with address space
18833  if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18835  Diag(Loc, diag::err_field_with_address_space);
18836  Record->setInvalidDecl();
18837  InvalidDecl = true;
18838  }
18839 
18840  if (LangOpts.OpenCL) {
18841  // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18842  // used as structure or union field: image, sampler, event or block types.
18843  if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18844  T->isBlockPointerType()) {
18845  Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18846  Record->setInvalidDecl();
18847  InvalidDecl = true;
18848  }
18849  // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18850  // is enabled.
18851  if (BitWidth && !getOpenCLOptions().isAvailableOption(
18852  "__cl_clang_bitfields", LangOpts)) {
18853  Diag(Loc, diag::err_opencl_bitfields);
18854  InvalidDecl = true;
18855  }
18856  }
18857 
18858  // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18859  if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18860  T.hasQualifiers()) {
18861  InvalidDecl = true;
18862  Diag(Loc, diag::err_anon_bitfield_qualifiers);
18863  }
18864 
18865  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18866  // than a variably modified type.
18867  if (!InvalidDecl && T->isVariablyModifiedType()) {
18868  if (!tryToFixVariablyModifiedVarType(
18869  TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18870  InvalidDecl = true;
18871  }
18872 
18873  // Fields can not have abstract class types
18874  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18875  diag::err_abstract_type_in_decl,
18876  AbstractFieldType))
18877  InvalidDecl = true;
18878 
18879  if (InvalidDecl)
18880  BitWidth = nullptr;
18881  // If this is declared as a bit-field, check the bit-field.
18882  if (BitWidth) {
18883  BitWidth =
18884  VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18885  if (!BitWidth) {
18886  InvalidDecl = true;
18887  BitWidth = nullptr;
18888  }
18889  }
18890 
18891  // Check that 'mutable' is consistent with the type of the declaration.
18892  if (!InvalidDecl && Mutable) {
18893  unsigned DiagID = 0;
18894  if (T->isReferenceType())
18895  DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18896  : diag::err_mutable_reference;
18897  else if (T.isConstQualified())
18898  DiagID = diag::err_mutable_const;
18899 
18900  if (DiagID) {
18901  SourceLocation ErrLoc = Loc;
18902  if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18903  ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18904  Diag(ErrLoc, DiagID);
18905  if (DiagID != diag::ext_mutable_reference) {
18906  Mutable = false;
18907  InvalidDecl = true;
18908  }
18909  }
18910  }
18911 
18912  // C++11 [class.union]p8 (DR1460):
18913  // At most one variant member of a union may have a
18914  // brace-or-equal-initializer.
18915  if (InitStyle != ICIS_NoInit)
18916  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18917 
18918  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18919  BitWidth, Mutable, InitStyle);
18920  if (InvalidDecl)
18921  NewFD->setInvalidDecl();
18922 
18923  if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18924  !PrevDecl->isPlaceholderVar(getLangOpts())) {
18925  Diag(Loc, diag::err_duplicate_member) << II;
18926  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18927  NewFD->setInvalidDecl();
18928  }
18929 
18930  if (!InvalidDecl && getLangOpts().CPlusPlus) {
18931  if (Record->isUnion()) {
18932  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18933  CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18934  if (RDecl->getDefinition()) {
18935  // C++ [class.union]p1: An object of a class with a non-trivial
18936  // constructor, a non-trivial copy constructor, a non-trivial
18937  // destructor, or a non-trivial copy assignment operator
18938  // cannot be a member of a union, nor can an array of such
18939  // objects.
18940  if (CheckNontrivialField(NewFD))
18941  NewFD->setInvalidDecl();
18942  }
18943  }
18944 
18945  // C++ [class.union]p1: If a union contains a member of reference type,
18946  // the program is ill-formed, except when compiling with MSVC extensions
18947  // enabled.
18948  if (EltTy->isReferenceType()) {
18949  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18950  diag::ext_union_member_of_reference_type :
18951  diag::err_union_member_of_reference_type)
18952  << NewFD->getDeclName() << EltTy;
18953  if (!getLangOpts().MicrosoftExt)
18954  NewFD->setInvalidDecl();
18955  }
18956  }
18957  }
18958 
18959  // FIXME: We need to pass in the attributes given an AST
18960  // representation, not a parser representation.
18961  if (D) {
18962  // FIXME: The current scope is almost... but not entirely... correct here.
18963  ProcessDeclAttributes(getCurScope(), NewFD, *D);
18964 
18965  if (NewFD->hasAttrs())
18966  CheckAlignasUnderalignment(NewFD);
18967  }
18968 
18969  // In auto-retain/release, infer strong retension for fields of
18970  // retainable type.
18971  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18972  NewFD->setInvalidDecl();
18973 
18974  if (T.isObjCGCWeak())
18975  Diag(Loc, diag::warn_attribute_weak_on_field);
18976 
18977  // PPC MMA non-pointer types are not allowed as field types.
18978  if (Context.getTargetInfo().getTriple().isPPC64() &&
18979  CheckPPCMMAType(T, NewFD->getLocation()))
18980  NewFD->setInvalidDecl();
18981 
18982  NewFD->setAccess(AS);
18983  return NewFD;
18984 }
18985 
18987  assert(FD);
18988  assert(getLangOpts().CPlusPlus && "valid check only for C++");
18989 
18990  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18991  return false;
18992 
18993  QualType EltTy = Context.getBaseElementType(FD->getType());
18994  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18995  CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18996  if (RDecl->getDefinition()) {
18997  // We check for copy constructors before constructors
18998  // because otherwise we'll never get complaints about
18999  // copy constructors.
19000 
19002  // We're required to check for any non-trivial constructors. Since the
19003  // implicit default constructor is suppressed if there are any
19004  // user-declared constructors, we just need to check that there is a
19005  // trivial default constructor and a trivial copy constructor. (We don't
19006  // worry about move constructors here, since this is a C++98 check.)
19007  if (RDecl->hasNonTrivialCopyConstructor())
19009  else if (!RDecl->hasTrivialDefaultConstructor())
19011  else if (RDecl->hasNonTrivialCopyAssignment())
19013  else if (RDecl->hasNonTrivialDestructor())
19015 
19017  if (!getLangOpts().CPlusPlus11 &&
19018  getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
19019  // Objective-C++ ARC: it is an error to have a non-trivial field of
19020  // a union. However, system headers in Objective-C programs
19021  // occasionally have Objective-C lifetime objects within unions,
19022  // and rather than cause the program to fail, we make those
19023  // members unavailable.
19024  SourceLocation Loc = FD->getLocation();
19025  if (getSourceManager().isInSystemHeader(Loc)) {
19026  if (!FD->hasAttr<UnavailableAttr>())
19027  FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
19028  UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19029  return false;
19030  }
19031  }
19032 
19033  Diag(
19034  FD->getLocation(),
19035  getLangOpts().CPlusPlus11
19036  ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19037  : diag::err_illegal_union_or_anon_struct_member)
19038  << FD->getParent()->isUnion() << FD->getDeclName()
19039  << llvm::to_underlying(member);
19040  DiagnoseNontrivial(RDecl, member);
19041  return !getLangOpts().CPlusPlus11;
19042  }
19043  }
19044  }
19045 
19046  return false;
19047 }
19048 
19049 /// TranslateIvarVisibility - Translate visibility from a token ID to an
19050 /// AST enum value.
19053  switch (ivarVisibility) {
19054  default: llvm_unreachable("Unknown visitibility kind");
19055  case tok::objc_private: return ObjCIvarDecl::Private;
19056  case tok::objc_public: return ObjCIvarDecl::Public;
19057  case tok::objc_protected: return ObjCIvarDecl::Protected;
19058  case tok::objc_package: return ObjCIvarDecl::Package;
19059  }
19060 }
19061 
19062 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
19063 /// in order to create an IvarDecl object for it.
19065  Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
19066 
19067  const IdentifierInfo *II = D.getIdentifier();
19068  SourceLocation Loc = DeclStart;
19069  if (II) Loc = D.getIdentifierLoc();
19070 
19071  // FIXME: Unnamed fields can be handled in various different ways, for
19072  // example, unnamed unions inject all members into the struct namespace!
19073 
19074  TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19075  QualType T = TInfo->getType();
19076 
19077  if (BitWidth) {
19078  // 6.7.2.1p3, 6.7.2.1p4
19079  BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
19080  if (!BitWidth)
19081  D.setInvalidType();
19082  } else {
19083  // Not a bitfield.
19084 
19085  // validate II.
19086 
19087  }
19088  if (T->isReferenceType()) {
19089  Diag(Loc, diag::err_ivar_reference_type);
19090  D.setInvalidType();
19091  }
19092  // C99 6.7.2.1p8: A member of a structure or union may have any type other
19093  // than a variably modified type.
19094  else if (T->isVariablyModifiedType()) {
19095  if (!tryToFixVariablyModifiedVarType(
19096  TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
19097  D.setInvalidType();
19098  }
19099 
19100  // Get the visibility (access control) for this ivar.
19102  Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
19104  // Must set ivar's DeclContext to its enclosing interface.
19105  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
19106  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
19107  return nullptr;
19108  ObjCContainerDecl *EnclosingContext;
19109  if (ObjCImplementationDecl *IMPDecl =
19110  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19111  if (LangOpts.ObjCRuntime.isFragile()) {
19112  // Case of ivar declared in an implementation. Context is that of its class.
19113  EnclosingContext = IMPDecl->getClassInterface();
19114  assert(EnclosingContext && "Implementation has no class interface!");
19115  }
19116  else
19117  EnclosingContext = EnclosingDecl;
19118  } else {
19119  if (ObjCCategoryDecl *CDecl =
19120  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19121  if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
19122  Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
19123  return nullptr;
19124  }
19125  }
19126  EnclosingContext = EnclosingDecl;
19127  }
19128 
19129  // Construct the decl.
19131  Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
19132 
19133  if (T->containsErrors())
19134  NewID->setInvalidDecl();
19135 
19136  if (II) {
19137  NamedDecl *PrevDecl =
19138  LookupSingleName(S, II, Loc, LookupMemberName,
19140  if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
19141  && !isa<TagDecl>(PrevDecl)) {
19142  Diag(Loc, diag::err_duplicate_member) << II;
19143  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19144  NewID->setInvalidDecl();
19145  }
19146  }
19147 
19148  // Process attributes attached to the ivar.
19149  ProcessDeclAttributes(S, NewID, D);
19150 
19151  if (D.isInvalidType())
19152  NewID->setInvalidDecl();
19153 
19154  // In ARC, infer 'retaining' for ivars of retainable type.
19155  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
19156  NewID->setInvalidDecl();
19157 
19159  NewID->setModulePrivate();
19160 
19161  if (II) {
19162  // FIXME: When interfaces are DeclContexts, we'll need to add
19163  // these to the interface.
19164  S->AddDecl(NewID);
19165  IdResolver.AddDecl(NewID);
19166  }
19167 
19168  if (LangOpts.ObjCRuntime.isNonFragile() &&
19169  !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
19170  Diag(Loc, diag::warn_ivars_in_interface);
19171 
19172  return NewID;
19173 }
19174 
19175 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
19176 /// class and class extensions. For every class \@interface and class
19177 /// extension \@interface, if the last ivar is a bitfield of any type,
19178 /// then add an implicit `char :0` ivar to the end of that interface.
19180  SmallVectorImpl<Decl *> &AllIvarDecls) {
19181  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19182  return;
19183 
19184  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19185  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19186 
19187  if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
19188  return;
19189  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19190  if (!ID) {
19191  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19192  if (!CD->IsClassExtension())
19193  return;
19194  }
19195  // No need to add this to end of @implementation.
19196  else
19197  return;
19198  }
19199  // All conditions are met. Add a new bitfield to the tail end of ivars.
19200  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19201  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19202 
19203  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
19204  DeclLoc, DeclLoc, nullptr,
19205  Context.CharTy,
19206  Context.getTrivialTypeSourceInfo(Context.CharTy,
19207  DeclLoc),
19209  true);
19210  AllIvarDecls.push_back(Ivar);
19211 }
19212 
19213 /// [class.dtor]p4:
19214 /// At the end of the definition of a class, overload resolution is
19215 /// performed among the prospective destructors declared in that class with
19216 /// an empty argument list to select the destructor for the class, also
19217 /// known as the selected destructor.
19218 ///
19219 /// We do the overload resolution here, then mark the selected constructor in the AST.
19220 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19222  if (!Record->hasUserDeclaredDestructor()) {
19223  return;
19224  }
19225 
19226  SourceLocation Loc = Record->getLocation();
19228 
19229  for (auto *Decl : Record->decls()) {
19230  if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19231  if (DD->isInvalidDecl())
19232  continue;
19233  S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19234  OCS);
19235  assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19236  }
19237  }
19238 
19239  if (OCS.empty()) {
19240  return;
19241  }
19243  unsigned Msg = 0;
19244  OverloadCandidateDisplayKind DisplayKind;
19245 
19246  switch (OCS.BestViableFunction(S, Loc, Best)) {
19247  case OR_Success:
19248  case OR_Deleted:
19249  Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19250  break;
19251 
19252  case OR_Ambiguous:
19253  Msg = diag::err_ambiguous_destructor;
19254  DisplayKind = OCD_AmbiguousCandidates;
19255  break;
19256 
19257  case OR_No_Viable_Function:
19258  Msg = diag::err_no_viable_destructor;
19259  DisplayKind = OCD_AllCandidates;
19260  break;
19261  }
19262 
19263  if (Msg) {
19264  // OpenCL have got their own thing going with destructors. It's slightly broken,
19265  // but we allow it.
19266  if (!S.LangOpts.OpenCL) {
19267  PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19268  OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19269  Record->setInvalidDecl();
19270  }
19271  // It's a bit hacky: At this point we've raised an error but we want the
19272  // rest of the compiler to continue somehow working. However almost
19273  // everything we'll try to do with the class will depend on there being a
19274  // destructor. So let's pretend the first one is selected and hope for the
19275  // best.
19276  Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19277  }
19278 }
19279 
19280 /// [class.mem.special]p5
19281 /// Two special member functions are of the same kind if:
19282 /// - they are both default constructors,
19283 /// - they are both copy or move constructors with the same first parameter
19284 /// type, or
19285 /// - they are both copy or move assignment operators with the same first
19286 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19288  CXXMethodDecl *M1,
19289  CXXMethodDecl *M2,
19290  CXXSpecialMemberKind CSM) {
19291  // We don't want to compare templates to non-templates: See
19292  // https://github.com/llvm/llvm-project/issues/59206
19294  return bool(M1->getDescribedFunctionTemplate()) ==
19296  // FIXME: better resolve CWG
19297  // https://cplusplus.github.io/CWG/issues/2787.html
19298  if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19299  M2->getNonObjectParameter(0)->getType()))
19300  return false;
19303  return false;
19304 
19305  return true;
19306 }
19307 
19308 /// [class.mem.special]p6:
19309 /// An eligible special member function is a special member function for which:
19310 /// - the function is not deleted,
19311 /// - the associated constraints, if any, are satisfied, and
19312 /// - no special member function of the same kind whose associated constraints
19313 /// [CWG2595], if any, are satisfied is more constrained.
19315  ArrayRef<CXXMethodDecl *> Methods,
19316  CXXSpecialMemberKind CSM) {
19317  SmallVector<bool, 4> SatisfactionStatus;
19318 
19319  for (CXXMethodDecl *Method : Methods) {
19320  const Expr *Constraints = Method->getTrailingRequiresClause();
19321  if (!Constraints)
19322  SatisfactionStatus.push_back(true);
19323  else {
19324  ConstraintSatisfaction Satisfaction;
19325  if (S.CheckFunctionConstraints(Method, Satisfaction))
19326  SatisfactionStatus.push_back(false);
19327  else
19328  SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19329  }
19330  }
19331 
19332  for (size_t i = 0; i < Methods.size(); i++) {
19333  if (!SatisfactionStatus[i])
19334  continue;
19335  CXXMethodDecl *Method = Methods[i];
19336  CXXMethodDecl *OrigMethod = Method;
19337  if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19338  OrigMethod = cast<CXXMethodDecl>(MF);
19339 
19340  const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
19341  bool AnotherMethodIsMoreConstrained = false;
19342  for (size_t j = 0; j < Methods.size(); j++) {
19343  if (i == j || !SatisfactionStatus[j])
19344  continue;
19345  CXXMethodDecl *OtherMethod = Methods[j];
19346  if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19347  OtherMethod = cast<CXXMethodDecl>(MF);
19348 
19349  if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19350  CSM))
19351  continue;
19352 
19353  const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
19354  if (!OtherConstraints)
19355  continue;
19356  if (!Constraints) {
19357  AnotherMethodIsMoreConstrained = true;
19358  break;
19359  }
19360  if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
19361  {Constraints},
19362  AnotherMethodIsMoreConstrained)) {
19363  // There was an error with the constraints comparison. Exit the loop
19364  // and don't consider this function eligible.
19365  AnotherMethodIsMoreConstrained = true;
19366  }
19367  if (AnotherMethodIsMoreConstrained)
19368  break;
19369  }
19370  // FIXME: Do not consider deleted methods as eligible after implementing
19371  // DR1734 and DR1496.
19372  if (!AnotherMethodIsMoreConstrained) {
19373  Method->setIneligibleOrNotSelected(false);
19374  Record->addedEligibleSpecialMemberFunction(Method,
19375  1 << llvm::to_underlying(CSM));
19376  }
19377  }
19378 }
19379 
19381  CXXRecordDecl *Record) {
19382  SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19383  SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19384  SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19385  SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19386  SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19387 
19388  for (auto *Decl : Record->decls()) {
19389  auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19390  if (!MD) {
19391  auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19392  if (FTD)
19393  MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19394  }
19395  if (!MD)
19396  continue;
19397  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19398  if (CD->isInvalidDecl())
19399  continue;
19400  if (CD->isDefaultConstructor())
19401  DefaultConstructors.push_back(MD);
19402  else if (CD->isCopyConstructor())
19403  CopyConstructors.push_back(MD);
19404  else if (CD->isMoveConstructor())
19405  MoveConstructors.push_back(MD);
19406  } else if (MD->isCopyAssignmentOperator()) {
19407  CopyAssignmentOperators.push_back(MD);
19408  } else if (MD->isMoveAssignmentOperator()) {
19409  MoveAssignmentOperators.push_back(MD);
19410  }
19411  }
19412 
19413  SetEligibleMethods(S, Record, DefaultConstructors,
19415  SetEligibleMethods(S, Record, CopyConstructors,
19417  SetEligibleMethods(S, Record, MoveConstructors,
19419  SetEligibleMethods(S, Record, CopyAssignmentOperators,
19421  SetEligibleMethods(S, Record, MoveAssignmentOperators,
19423 }
19424 
19425 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19426  ArrayRef<Decl *> Fields, SourceLocation LBrac,
19427  SourceLocation RBrac,
19428  const ParsedAttributesView &Attrs) {
19429  assert(EnclosingDecl && "missing record or interface decl");
19430 
19431  // If this is an Objective-C @implementation or category and we have
19432  // new fields here we should reset the layout of the interface since
19433  // it will now change.
19434  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19435  ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19436  switch (DC->getKind()) {
19437  default: break;
19438  case Decl::ObjCCategory:
19439  Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19440  break;
19441  case Decl::ObjCImplementation:
19442  Context.
19443  ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19444  break;
19445  }
19446  }
19447 
19448  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19449  CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19450 
19451  // Start counting up the number of named members; make sure to include
19452  // members of anonymous structs and unions in the total.
19453  unsigned NumNamedMembers = 0;
19454  if (Record) {
19455  for (const auto *I : Record->decls()) {
19456  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19457  if (IFD->getDeclName())
19458  ++NumNamedMembers;
19459  }
19460  }
19461 
19462  // Verify that all the fields are okay.
19463  SmallVector<FieldDecl*, 32> RecFields;
19464 
19465  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19466  i != end; ++i) {
19467  FieldDecl *FD = cast<FieldDecl>(*i);
19468 
19469  // Get the type for the field.
19470  const Type *FDTy = FD->getType().getTypePtr();
19471 
19472  if (!FD->isAnonymousStructOrUnion()) {
19473  // Remember all fields written by the user.
19474  RecFields.push_back(FD);
19475  }
19476 
19477  // If the field is already invalid for some reason, don't emit more
19478  // diagnostics about it.
19479  if (FD->isInvalidDecl()) {
19480  EnclosingDecl->setInvalidDecl();
19481  continue;
19482  }
19483 
19484  // C99 6.7.2.1p2:
19485  // A structure or union shall not contain a member with
19486  // incomplete or function type (hence, a structure shall not
19487  // contain an instance of itself, but may contain a pointer to
19488  // an instance of itself), except that the last member of a
19489  // structure with more than one named member may have incomplete
19490  // array type; such a structure (and any union containing,
19491  // possibly recursively, a member that is such a structure)
19492  // shall not be a member of a structure or an element of an
19493  // array.
19494  bool IsLastField = (i + 1 == Fields.end());
19495  if (FDTy->isFunctionType()) {
19496  // Field declared as a function.
19497  Diag(FD->getLocation(), diag::err_field_declared_as_function)
19498  << FD->getDeclName();
19499  FD->setInvalidDecl();
19500  EnclosingDecl->setInvalidDecl();
19501  continue;
19502  } else if (FDTy->isIncompleteArrayType() &&
19503  (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19504  if (Record) {
19505  // Flexible array member.
19506  // Microsoft and g++ is more permissive regarding flexible array.
19507  // It will accept flexible array in union and also
19508  // as the sole element of a struct/class.
19509  unsigned DiagID = 0;
19510  if (!Record->isUnion() && !IsLastField) {
19511  Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19512  << FD->getDeclName() << FD->getType()
19513  << llvm::to_underlying(Record->getTagKind());
19514  Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19515  FD->setInvalidDecl();
19516  EnclosingDecl->setInvalidDecl();
19517  continue;
19518  } else if (Record->isUnion())
19519  DiagID = getLangOpts().MicrosoftExt
19520  ? diag::ext_flexible_array_union_ms
19521  : diag::ext_flexible_array_union_gnu;
19522  else if (NumNamedMembers < 1)
19523  DiagID = getLangOpts().MicrosoftExt
19524  ? diag::ext_flexible_array_empty_aggregate_ms
19525  : diag::ext_flexible_array_empty_aggregate_gnu;
19526 
19527  if (DiagID)
19528  Diag(FD->getLocation(), DiagID)
19529  << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19530  // While the layout of types that contain virtual bases is not specified
19531  // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19532  // virtual bases after the derived members. This would make a flexible
19533  // array member declared at the end of an object not adjacent to the end
19534  // of the type.
19535  if (CXXRecord && CXXRecord->getNumVBases() != 0)
19536  Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19537  << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19538  if (!getLangOpts().C99)
19539  Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19540  << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19541 
19542  // If the element type has a non-trivial destructor, we would not
19543  // implicitly destroy the elements, so disallow it for now.
19544  //
19545  // FIXME: GCC allows this. We should probably either implicitly delete
19546  // the destructor of the containing class, or just allow this.
19547  QualType BaseElem = Context.getBaseElementType(FD->getType());
19548  if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19549  Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19550  << FD->getDeclName() << FD->getType();
19551  FD->setInvalidDecl();
19552  EnclosingDecl->setInvalidDecl();
19553  continue;
19554  }
19555  // Okay, we have a legal flexible array member at the end of the struct.
19556  Record->setHasFlexibleArrayMember(true);
19557  } else {
19558  // In ObjCContainerDecl ivars with incomplete array type are accepted,
19559  // unless they are followed by another ivar. That check is done
19560  // elsewhere, after synthesized ivars are known.
19561  }
19562  } else if (!FDTy->isDependentType() &&
19563  RequireCompleteSizedType(
19564  FD->getLocation(), FD->getType(),
19565  diag::err_field_incomplete_or_sizeless)) {
19566  // Incomplete type
19567  FD->setInvalidDecl();
19568  EnclosingDecl->setInvalidDecl();
19569  continue;
19570  } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19571  if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19572  // A type which contains a flexible array member is considered to be a
19573  // flexible array member.
19574  Record->setHasFlexibleArrayMember(true);
19575  if (!Record->isUnion()) {
19576  // If this is a struct/class and this is not the last element, reject
19577  // it. Note that GCC supports variable sized arrays in the middle of
19578  // structures.
19579  if (!IsLastField)
19580  Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19581  << FD->getDeclName() << FD->getType();
19582  else {
19583  // We support flexible arrays at the end of structs in
19584  // other structs as an extension.
19585  Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19586  << FD->getDeclName();
19587  }
19588  }
19589  }
19590  if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19591  RequireNonAbstractType(FD->getLocation(), FD->getType(),
19592  diag::err_abstract_type_in_decl,
19593  AbstractIvarType)) {
19594  // Ivars can not have abstract class types
19595  FD->setInvalidDecl();
19596  }
19597  if (Record && FDTTy->getDecl()->hasObjectMember())
19598  Record->setHasObjectMember(true);
19599  if (Record && FDTTy->getDecl()->hasVolatileMember())
19600  Record->setHasVolatileMember(true);
19601  } else if (FDTy->isObjCObjectType()) {
19602  /// A field cannot be an Objective-c object
19603  Diag(FD->getLocation(), diag::err_statically_allocated_object)
19604  << FixItHint::CreateInsertion(FD->getLocation(), "*");
19605  QualType T = Context.getObjCObjectPointerType(FD->getType());
19606  FD->setType(T);
19607  } else if (Record && Record->isUnion() &&
19609  getSourceManager().isInSystemHeader(FD->getLocation()) &&
19610  !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19612  !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19613  // For backward compatibility, fields of C unions declared in system
19614  // headers that have non-trivial ObjC ownership qualifications are marked
19615  // as unavailable unless the qualifier is explicit and __strong. This can
19616  // break ABI compatibility between programs compiled with ARC and MRR, but
19617  // is a better option than rejecting programs using those unions under
19618  // ARC.
19619  FD->addAttr(UnavailableAttr::CreateImplicit(
19620  Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19621  FD->getLocation()));
19622  } else if (getLangOpts().ObjC &&
19623  getLangOpts().getGC() != LangOptions::NonGC && Record &&
19624  !Record->hasObjectMember()) {
19625  if (FD->getType()->isObjCObjectPointerType() ||
19626  FD->getType().isObjCGCStrong())
19627  Record->setHasObjectMember(true);
19628  else if (Context.getAsArrayType(FD->getType())) {
19629  QualType BaseType = Context.getBaseElementType(FD->getType());
19630  if (BaseType->isRecordType() &&
19631  BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19632  Record->setHasObjectMember(true);
19633  else if (BaseType->isObjCObjectPointerType() ||
19634  BaseType.isObjCGCStrong())
19635  Record->setHasObjectMember(true);
19636  }
19637  }
19638 
19639  if (Record && !getLangOpts().CPlusPlus &&
19640  !shouldIgnoreForRecordTriviality(FD)) {
19641  QualType FT = FD->getType();
19643  Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19645  Record->isUnion())
19646  Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19647  }
19650  Record->setNonTrivialToPrimitiveCopy(true);
19651  if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19652  Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19653  }
19654  if (FT.isDestructedType()) {
19655  Record->setNonTrivialToPrimitiveDestroy(true);
19656  Record->setParamDestroyedInCallee(true);
19657  if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19658  Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19659  }
19660 
19661  if (const auto *RT = FT->getAs<RecordType>()) {
19662  if (RT->getDecl()->getArgPassingRestrictions() ==
19664  Record->setArgPassingRestrictions(
19666  } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19667  Record->setArgPassingRestrictions(
19669  }
19670 
19671  if (Record && FD->getType().isVolatileQualified())
19672  Record->setHasVolatileMember(true);
19673  // Keep track of the number of named members.
19674  if (FD->getIdentifier())
19675  ++NumNamedMembers;
19676  }
19677 
19678  // Okay, we successfully defined 'Record'.
19679  if (Record) {
19680  bool Completed = false;
19681  if (S) {
19682  Scope *Parent = S->getParent();
19683  if (Parent && Parent->isTypeAliasScope() &&
19684  Parent->isTemplateParamScope())
19685  Record->setInvalidDecl();
19686  }
19687 
19688  if (CXXRecord) {
19689  if (!CXXRecord->isInvalidDecl()) {
19690  // Set access bits correctly on the directly-declared conversions.
19692  I = CXXRecord->conversion_begin(),
19693  E = CXXRecord->conversion_end(); I != E; ++I)
19694  I.setAccess((*I)->getAccess());
19695  }
19696 
19697  // Add any implicitly-declared members to this class.
19698  AddImplicitlyDeclaredMembersToClass(CXXRecord);
19699 
19700  if (!CXXRecord->isDependentType()) {
19701  if (!CXXRecord->isInvalidDecl()) {
19702  // If we have virtual base classes, we may end up finding multiple
19703  // final overriders for a given virtual function. Check for this
19704  // problem now.
19705  if (CXXRecord->getNumVBases()) {
19706  CXXFinalOverriderMap FinalOverriders;
19707  CXXRecord->getFinalOverriders(FinalOverriders);
19708 
19709  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19710  MEnd = FinalOverriders.end();
19711  M != MEnd; ++M) {
19712  for (OverridingMethods::iterator SO = M->second.begin(),
19713  SOEnd = M->second.end();
19714  SO != SOEnd; ++SO) {
19715  assert(SO->second.size() > 0 &&
19716  "Virtual function without overriding functions?");
19717  if (SO->second.size() == 1)
19718  continue;
19719 
19720  // C++ [class.virtual]p2:
19721  // In a derived class, if a virtual member function of a base
19722  // class subobject has more than one final overrider the
19723  // program is ill-formed.
19724  Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19725  << (const NamedDecl *)M->first << Record;
19726  Diag(M->first->getLocation(),
19727  diag::note_overridden_virtual_function);
19729  OM = SO->second.begin(),
19730  OMEnd = SO->second.end();
19731  OM != OMEnd; ++OM)
19732  Diag(OM->Method->getLocation(), diag::note_final_overrider)
19733  << (const NamedDecl *)M->first << OM->Method->getParent();
19734 
19735  Record->setInvalidDecl();
19736  }
19737  }
19738  CXXRecord->completeDefinition(&FinalOverriders);
19739  Completed = true;
19740  }
19741  }
19742  ComputeSelectedDestructor(*this, CXXRecord);
19743  ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19744  }
19745  }
19746 
19747  if (!Completed)
19748  Record->completeDefinition();
19749 
19750  // Handle attributes before checking the layout.
19751  ProcessDeclAttributeList(S, Record, Attrs);
19752 
19753  // Check to see if a FieldDecl is a pointer to a function.
19754  auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19755  const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19756  if (!FD) {
19757  // Check whether this is a forward declaration that was inserted by
19758  // Clang. This happens when a non-forward declared / defined type is
19759  // used, e.g.:
19760  //
19761  // struct foo {
19762  // struct bar *(*f)();
19763  // struct bar *(*g)();
19764  // };
19765  //
19766  // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19767  // incomplete definition.
19768  if (const auto *TD = dyn_cast<TagDecl>(D))
19769  return !TD->isCompleteDefinition();
19770  return false;
19771  }
19772  QualType FieldType = FD->getType().getDesugaredType(Context);
19773  if (isa<PointerType>(FieldType)) {
19774  QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19775  return PointeeType.getDesugaredType(Context)->isFunctionType();
19776  }
19777  return false;
19778  };
19779 
19780  // Maybe randomize the record's decls. We automatically randomize a record
19781  // of function pointers, unless it has the "no_randomize_layout" attribute.
19782  if (!getLangOpts().CPlusPlus &&
19783  (Record->hasAttr<RandomizeLayoutAttr>() ||
19784  (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19785  llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19786  !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19787  !Record->isRandomized()) {
19788  SmallVector<Decl *, 32> NewDeclOrdering;
19790  NewDeclOrdering))
19791  Record->reorderDecls(NewDeclOrdering);
19792  }
19793 
19794  // We may have deferred checking for a deleted destructor. Check now.
19795  if (CXXRecord) {
19796  auto *Dtor = CXXRecord->getDestructor();
19797  if (Dtor && Dtor->isImplicit() &&
19798  ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {
19799  CXXRecord->setImplicitDestructorIsDeleted();
19800  SetDeclDeleted(Dtor, CXXRecord->getLocation());
19801  }
19802  }
19803 
19804  if (Record->hasAttrs()) {
19805  CheckAlignasUnderalignment(Record);
19806 
19807  if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19808  checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19809  IA->getRange(), IA->getBestCase(),
19810  IA->getInheritanceModel());
19811  }
19812 
19813  // Check if the structure/union declaration is a type that can have zero
19814  // size in C. For C this is a language extension, for C++ it may cause
19815  // compatibility problems.
19816  bool CheckForZeroSize;
19817  if (!getLangOpts().CPlusPlus) {
19818  CheckForZeroSize = true;
19819  } else {
19820  // For C++ filter out types that cannot be referenced in C code.
19821  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19822  CheckForZeroSize =
19823  CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19824  !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19825  CXXRecord->isCLike();
19826  }
19827  if (CheckForZeroSize) {
19828  bool ZeroSize = true;
19829  bool IsEmpty = true;
19830  unsigned NonBitFields = 0;
19831  for (RecordDecl::field_iterator I = Record->field_begin(),
19832  E = Record->field_end();
19833  (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19834  IsEmpty = false;
19835  if (I->isUnnamedBitField()) {
19836  if (!I->isZeroLengthBitField(Context))
19837  ZeroSize = false;
19838  } else {
19839  ++NonBitFields;
19840  QualType FieldType = I->getType();
19841  if (FieldType->isIncompleteType() ||
19842  !Context.getTypeSizeInChars(FieldType).isZero())
19843  ZeroSize = false;
19844  }
19845  }
19846 
19847  // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19848  // allowed in C++, but warn if its declaration is inside
19849  // extern "C" block.
19850  if (ZeroSize) {
19851  Diag(RecLoc, getLangOpts().CPlusPlus ?
19852  diag::warn_zero_size_struct_union_in_extern_c :
19853  diag::warn_zero_size_struct_union_compat)
19854  << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19855  }
19856 
19857  // Structs without named members are extension in C (C99 6.7.2.1p7),
19858  // but are accepted by GCC.
19859  if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19860  Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19861  diag::ext_no_named_members_in_struct_union)
19862  << Record->isUnion();
19863  }
19864  }
19865  } else {
19866  ObjCIvarDecl **ClsFields =
19867  reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19868  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19869  ID->setEndOfDefinitionLoc(RBrac);
19870  // Add ivar's to class's DeclContext.
19871  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19872  ClsFields[i]->setLexicalDeclContext(ID);
19873  ID->addDecl(ClsFields[i]);
19874  }
19875  // Must enforce the rule that ivars in the base classes may not be
19876  // duplicates.
19877  if (ID->getSuperClass())
19878  DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19879  } else if (ObjCImplementationDecl *IMPDecl =
19880  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19881  assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19882  for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19883  // Ivar declared in @implementation never belongs to the implementation.
19884  // Only it is in implementation's lexical context.
19885  ClsFields[I]->setLexicalDeclContext(IMPDecl);
19886  CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19887  IMPDecl->setIvarLBraceLoc(LBrac);
19888  IMPDecl->setIvarRBraceLoc(RBrac);
19889  } else if (ObjCCategoryDecl *CDecl =
19890  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19891  // case of ivars in class extension; all other cases have been
19892  // reported as errors elsewhere.
19893  // FIXME. Class extension does not have a LocEnd field.
19894  // CDecl->setLocEnd(RBrac);
19895  // Add ivar's to class extension's DeclContext.
19896  // Diagnose redeclaration of private ivars.
19897  ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19898  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19899  if (IDecl) {
19900  if (const ObjCIvarDecl *ClsIvar =
19901  IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19902  Diag(ClsFields[i]->getLocation(),
19903  diag::err_duplicate_ivar_declaration);
19904  Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19905  continue;
19906  }
19907  for (const auto *Ext : IDecl->known_extensions()) {
19908  if (const ObjCIvarDecl *ClsExtIvar
19909  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19910  Diag(ClsFields[i]->getLocation(),
19911  diag::err_duplicate_ivar_declaration);
19912  Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19913  continue;
19914  }
19915  }
19916  }
19917  ClsFields[i]->setLexicalDeclContext(CDecl);
19918  CDecl->addDecl(ClsFields[i]);
19919  }
19920  CDecl->setIvarLBraceLoc(LBrac);
19921  CDecl->setIvarRBraceLoc(RBrac);
19922  }
19923  }
19925 }
19926 
19927 /// Determine whether the given integral value is representable within
19928 /// the given type T.
19931  QualType T) {
19932  assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19933  "Integral type required!");
19934  unsigned BitWidth = Context.getIntWidth(T);
19935 
19936  if (Value.isUnsigned() || Value.isNonNegative()) {
19938  --BitWidth;
19939  return Value.getActiveBits() <= BitWidth;
19940  }
19941  return Value.getSignificantBits() <= BitWidth;
19942 }
19943 
19944 // Given an integral type, return the next larger integral type
19945 // (or a NULL type of no such type exists).
19947  // FIXME: Int128/UInt128 support, which also needs to be introduced into
19948  // enum checking below.
19949  assert((T->isIntegralType(Context) ||
19950  T->isEnumeralType()) && "Integral type required!");
19951  const unsigned NumTypes = 4;
19952  QualType SignedIntegralTypes[NumTypes] = {
19953  Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19954  };
19955  QualType UnsignedIntegralTypes[NumTypes] = {
19956  Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19957  Context.UnsignedLongLongTy
19958  };
19959 
19960  unsigned BitWidth = Context.getTypeSize(T);
19961  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19962  : UnsignedIntegralTypes;
19963  for (unsigned I = 0; I != NumTypes; ++I)
19964  if (Context.getTypeSize(Types[I]) > BitWidth)
19965  return Types[I];
19966 
19967  return QualType();
19968 }
19969 
19971  EnumConstantDecl *LastEnumConst,
19972  SourceLocation IdLoc,
19973  IdentifierInfo *Id,
19974  Expr *Val) {
19975  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19976  llvm::APSInt EnumVal(IntWidth);
19977  QualType EltTy;
19978 
19979  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19980  Val = nullptr;
19981 
19982  if (Val)
19983  Val = DefaultLvalueConversion(Val).get();
19984 
19985  if (Val) {
19986  if (Enum->isDependentType() || Val->isTypeDependent() ||
19987  Val->containsErrors())
19988  EltTy = Context.DependentTy;
19989  else {
19990  // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19991  // underlying type, but do allow it in all other contexts.
19992  if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19993  // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19994  // constant-expression in the enumerator-definition shall be a converted
19995  // constant expression of the underlying type.
19996  EltTy = Enum->getIntegerType();
19997  ExprResult Converted =
19998  CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19999  CCEK_Enumerator);
20000  if (Converted.isInvalid())
20001  Val = nullptr;
20002  else
20003  Val = Converted.get();
20004  } else if (!Val->isValueDependent() &&
20005  !(Val =
20006  VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
20007  .get())) {
20008  // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20009  } else {
20010  if (Enum->isComplete()) {
20011  EltTy = Enum->getIntegerType();
20012 
20013  // In Obj-C and Microsoft mode, require the enumeration value to be
20014  // representable in the underlying type of the enumeration. In C++11,
20015  // we perform a non-narrowing conversion as part of converted constant
20016  // expression checking.
20017  if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
20018  if (Context.getTargetInfo()
20019  .getTriple()
20020  .isWindowsMSVCEnvironment()) {
20021  Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20022  } else {
20023  Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20024  }
20025  }
20026 
20027  // Cast to the underlying type.
20028  Val = ImpCastExprToType(Val, EltTy,
20029  EltTy->isBooleanType() ? CK_IntegralToBoolean
20030  : CK_IntegralCast)
20031  .get();
20032  } else if (getLangOpts().CPlusPlus) {
20033  // C++11 [dcl.enum]p5:
20034  // If the underlying type is not fixed, the type of each enumerator
20035  // is the type of its initializing value:
20036  // - If an initializer is specified for an enumerator, the
20037  // initializing value has the same type as the expression.
20038  EltTy = Val->getType();
20039  } else {
20040  // C99 6.7.2.2p2:
20041  // The expression that defines the value of an enumeration constant
20042  // shall be an integer constant expression that has a value
20043  // representable as an int.
20044 
20045  // Complain if the value is not representable in an int.
20046  if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
20047  Diag(IdLoc, diag::ext_enum_value_not_int)
20048  << toString(EnumVal, 10) << Val->getSourceRange()
20049  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20050  else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20051  // Force the type of the expression to 'int'.
20052  Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20053  }
20054  EltTy = Val->getType();
20055  }
20056  }
20057  }
20058  }
20059 
20060  if (!Val) {
20061  if (Enum->isDependentType())
20062  EltTy = Context.DependentTy;
20063  else if (!LastEnumConst) {
20064  // C++0x [dcl.enum]p5:
20065  // If the underlying type is not fixed, the type of each enumerator
20066  // is the type of its initializing value:
20067  // - If no initializer is specified for the first enumerator, the
20068  // initializing value has an unspecified integral type.
20069  //
20070  // GCC uses 'int' for its unspecified integral type, as does
20071  // C99 6.7.2.2p3.
20072  if (Enum->isFixed()) {
20073  EltTy = Enum->getIntegerType();
20074  }
20075  else {
20076  EltTy = Context.IntTy;
20077  }
20078  } else {
20079  // Assign the last value + 1.
20080  EnumVal = LastEnumConst->getInitVal();
20081  ++EnumVal;
20082  EltTy = LastEnumConst->getType();
20083 
20084  // Check for overflow on increment.
20085  if (EnumVal < LastEnumConst->getInitVal()) {
20086  // C++0x [dcl.enum]p5:
20087  // If the underlying type is not fixed, the type of each enumerator
20088  // is the type of its initializing value:
20089  //
20090  // - Otherwise the type of the initializing value is the same as
20091  // the type of the initializing value of the preceding enumerator
20092  // unless the incremented value is not representable in that type,
20093  // in which case the type is an unspecified integral type
20094  // sufficient to contain the incremented value. If no such type
20095  // exists, the program is ill-formed.
20096  QualType T = getNextLargerIntegralType(Context, EltTy);
20097  if (T.isNull() || Enum->isFixed()) {
20098  // There is no integral type larger enough to represent this
20099  // value. Complain, then allow the value to wrap around.
20100  EnumVal = LastEnumConst->getInitVal();
20101  EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20102  ++EnumVal;
20103  if (Enum->isFixed())
20104  // When the underlying type is fixed, this is ill-formed.
20105  Diag(IdLoc, diag::err_enumerator_wrapped)
20106  << toString(EnumVal, 10)
20107  << EltTy;
20108  else
20109  Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20110  << toString(EnumVal, 10);
20111  } else {
20112  EltTy = T;
20113  }
20114 
20115  // Retrieve the last enumerator's value, extent that type to the
20116  // type that is supposed to be large enough to represent the incremented
20117  // value, then increment.
20118  EnumVal = LastEnumConst->getInitVal();
20119  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20120  EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20121  ++EnumVal;
20122 
20123  // If we're not in C++, diagnose the overflow of enumerator values,
20124  // which in C99 means that the enumerator value is not representable in
20125  // an int (C99 6.7.2.2p2). However, we support GCC's extension that
20126  // permits enumerator values that are representable in some larger
20127  // integral type.
20128  if (!getLangOpts().CPlusPlus && !T.isNull())
20129  Diag(IdLoc, diag::warn_enum_value_overflow);
20130  } else if (!getLangOpts().CPlusPlus &&
20131  !EltTy->isDependentType() &&
20132  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
20133  // Enforce C99 6.7.2.2p2 even when we compute the next value.
20134  Diag(IdLoc, diag::ext_enum_value_not_int)
20135  << toString(EnumVal, 10) << 1;
20136  }
20137  }
20138  }
20139 
20140  if (!EltTy->isDependentType()) {
20141  // Make the enumerator value match the signedness and size of the
20142  // enumerator's type.
20143  EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20144  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20145  }
20146 
20147  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20148  Val, EnumVal);
20149 }
20150 
20152  SourceLocation IILoc) {
20153  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20154  !getLangOpts().CPlusPlus)
20155  return SkipBodyInfo();
20156 
20157  // We have an anonymous enum definition. Look up the first enumerator to
20158  // determine if we should merge the definition with an existing one and
20159  // skip the body.
20160  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20161  forRedeclarationInCurContext());
20162  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20163  if (!PrevECD)
20164  return SkipBodyInfo();
20165 
20166  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20167  NamedDecl *Hidden;
20168  if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20169  SkipBodyInfo Skip;
20170  Skip.Previous = Hidden;
20171  return Skip;
20172  }
20173 
20174  return SkipBodyInfo();
20175 }
20176 
20177 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20179  const ParsedAttributesView &Attrs,
20180  SourceLocation EqualLoc, Expr *Val) {
20181  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20182  EnumConstantDecl *LastEnumConst =
20183  cast_or_null<EnumConstantDecl>(lastEnumConst);
20184 
20185  // The scope passed in may not be a decl scope. Zip up the scope tree until
20186  // we find one that is.
20187  S = getNonFieldDeclScope(S);
20188 
20189  // Verify that there isn't already something declared with this name in this
20190  // scope.
20191  LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20193  LookupName(R, S);
20194  NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20195 
20196  if (PrevDecl && PrevDecl->isTemplateParameter()) {
20197  // Maybe we will complain about the shadowed template parameter.
20198  DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20199  // Just pretend that we didn't see the previous declaration.
20200  PrevDecl = nullptr;
20201  }
20202 
20203  // C++ [class.mem]p15:
20204  // If T is the name of a class, then each of the following shall have a name
20205  // different from T:
20206  // - every enumerator of every member of class T that is an unscoped
20207  // enumerated type
20208  if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20209  DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
20210  DeclarationNameInfo(Id, IdLoc));
20211 
20212  EnumConstantDecl *New =
20213  CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20214  if (!New)
20215  return nullptr;
20216 
20217  if (PrevDecl) {
20218  if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20219  // Check for other kinds of shadowing not already handled.
20220  CheckShadow(New, PrevDecl, R);
20221  }
20222 
20223  // When in C++, we may get a TagDecl with the same name; in this case the
20224  // enum constant will 'hide' the tag.
20225  assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20226  "Received TagDecl when not in C++!");
20227  if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20228  if (isa<EnumConstantDecl>(PrevDecl))
20229  Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20230  else
20231  Diag(IdLoc, diag::err_redefinition) << Id;
20232  notePreviousDefinition(PrevDecl, IdLoc);
20233  return nullptr;
20234  }
20235  }
20236 
20237  // Process attributes.
20238  ProcessDeclAttributeList(S, New, Attrs);
20239  AddPragmaAttributes(S, New);
20240  ProcessAPINotes(New);
20241 
20242  // Register this decl in the current scope stack.
20243  New->setAccess(TheEnumDecl->getAccess());
20244  PushOnScopeChains(New, S);
20245 
20246  ActOnDocumentableDecl(New);
20247 
20248  return New;
20249 }
20250 
20251 // Returns true when the enum initial expression does not trigger the
20252 // duplicate enum warning. A few common cases are exempted as follows:
20253 // Element2 = Element1
20254 // Element2 = Element1 + 1
20255 // Element2 = Element1 - 1
20256 // Where Element2 and Element1 are from the same enum.
20258  Expr *InitExpr = ECD->getInitExpr();
20259  if (!InitExpr)
20260  return true;
20261  InitExpr = InitExpr->IgnoreImpCasts();
20262 
20263  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20264  if (!BO->isAdditiveOp())
20265  return true;
20266  IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20267  if (!IL)
20268  return true;
20269  if (IL->getValue() != 1)
20270  return true;
20271 
20272  InitExpr = BO->getLHS();
20273  }
20274 
20275  // This checks if the elements are from the same enum.
20276  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20277  if (!DRE)
20278  return true;
20279 
20280  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20281  if (!EnumConstant)
20282  return true;
20283 
20284  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
20285  Enum)
20286  return true;
20287 
20288  return false;
20289 }
20290 
20291 // Emits a warning when an element is implicitly set a value that
20292 // a previous element has already been set to.
20294  EnumDecl *Enum, QualType EnumType) {
20295  // Avoid anonymous enums
20296  if (!Enum->getIdentifier())
20297  return;
20298 
20299  // Only check for small enums.
20300  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20301  return;
20302 
20303  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20304  return;
20305 
20306  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20307  typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20308 
20309  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20310 
20311  // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20312  typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20313 
20314  // Use int64_t as a key to avoid needing special handling for map keys.
20315  auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20316  llvm::APSInt Val = D->getInitVal();
20317  return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20318  };
20319 
20320  DuplicatesVector DupVector;
20321  ValueToVectorMap EnumMap;
20322 
20323  // Populate the EnumMap with all values represented by enum constants without
20324  // an initializer.
20325  for (auto *Element : Elements) {
20326  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20327 
20328  // Null EnumConstantDecl means a previous diagnostic has been emitted for
20329  // this constant. Skip this enum since it may be ill-formed.
20330  if (!ECD) {
20331  return;
20332  }
20333 
20334  // Constants with initializers are handled in the next loop.
20335  if (ECD->getInitExpr())
20336  continue;
20337 
20338  // Duplicate values are handled in the next loop.
20339  EnumMap.insert({EnumConstantToKey(ECD), ECD});
20340  }
20341 
20342  if (EnumMap.size() == 0)
20343  return;
20344 
20345  // Create vectors for any values that has duplicates.
20346  for (auto *Element : Elements) {
20347  // The last loop returned if any constant was null.
20348  EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
20349  if (!ValidDuplicateEnum(ECD, Enum))
20350  continue;
20351 
20352  auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20353  if (Iter == EnumMap.end())
20354  continue;
20355 
20356  DeclOrVector& Entry = Iter->second;
20357  if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
20358  // Ensure constants are different.
20359  if (D == ECD)
20360  continue;
20361 
20362  // Create new vector and push values onto it.
20363  auto Vec = std::make_unique<ECDVector>();
20364  Vec->push_back(D);
20365  Vec->push_back(ECD);
20366 
20367  // Update entry to point to the duplicates vector.
20368  Entry = Vec.get();
20369 
20370  // Store the vector somewhere we can consult later for quick emission of
20371  // diagnostics.
20372  DupVector.emplace_back(std::move(Vec));
20373  continue;
20374  }
20375 
20376  ECDVector *Vec = Entry.get<ECDVector*>();
20377  // Make sure constants are not added more than once.
20378  if (*Vec->begin() == ECD)
20379  continue;
20380 
20381  Vec->push_back(ECD);
20382  }
20383 
20384  // Emit diagnostics.
20385  for (const auto &Vec : DupVector) {
20386  assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20387 
20388  // Emit warning for one enum constant.
20389  auto *FirstECD = Vec->front();
20390  S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20391  << FirstECD << toString(FirstECD->getInitVal(), 10)
20392  << FirstECD->getSourceRange();
20393 
20394  // Emit one note for each of the remaining enum constants with
20395  // the same value.
20396  for (auto *ECD : llvm::drop_begin(*Vec))
20397  S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20398  << ECD << toString(ECD->getInitVal(), 10)
20399  << ECD->getSourceRange();
20400  }
20401 }
20402 
20403 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20404  bool AllowMask) const {
20405  assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20406  assert(ED->isCompleteDefinition() && "expected enum definition");
20407 
20408  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20409  llvm::APInt &FlagBits = R.first->second;
20410 
20411  if (R.second) {
20412  for (auto *E : ED->enumerators()) {
20413  const auto &EVal = E->getInitVal();
20414  // Only single-bit enumerators introduce new flag values.
20415  if (EVal.isPowerOf2())
20416  FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20417  }
20418  }
20419 
20420  // A value is in a flag enum if either its bits are a subset of the enum's
20421  // flag bits (the first condition) or we are allowing masks and the same is
20422  // true of its complement (the second condition). When masks are allowed, we
20423  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20424  //
20425  // While it's true that any value could be used as a mask, the assumption is
20426  // that a mask will have all of the insignificant bits set. Anything else is
20427  // likely a logic error.
20428  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20429  return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20430 }
20431 
20433  Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20434  const ParsedAttributesView &Attrs) {
20435  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20436  QualType EnumType = Context.getTypeDeclType(Enum);
20437 
20438  ProcessDeclAttributeList(S, Enum, Attrs);
20439  ProcessAPINotes(Enum);
20440 
20441  if (Enum->isDependentType()) {
20442  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20443  EnumConstantDecl *ECD =
20444  cast_or_null<EnumConstantDecl>(Elements[i]);
20445  if (!ECD) continue;
20446 
20447  ECD->setType(EnumType);
20448  }
20449 
20450  Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20451  return;
20452  }
20453 
20454  // TODO: If the result value doesn't fit in an int, it must be a long or long
20455  // long value. ISO C does not support this, but GCC does as an extension,
20456  // emit a warning.
20457  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20458  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20459  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20460 
20461  // Verify that all the values are okay, compute the size of the values, and
20462  // reverse the list.
20463  unsigned NumNegativeBits = 0;
20464  unsigned NumPositiveBits = 0;
20465 
20466  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20467  EnumConstantDecl *ECD =
20468  cast_or_null<EnumConstantDecl>(Elements[i]);
20469  if (!ECD) continue; // Already issued a diagnostic.
20470 
20471  const llvm::APSInt &InitVal = ECD->getInitVal();
20472 
20473  // Keep track of the size of positive and negative values.
20474  if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20475  // If the enumerator is zero that should still be counted as a positive
20476  // bit since we need a bit to store the value zero.
20477  unsigned ActiveBits = InitVal.getActiveBits();
20478  NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20479  } else {
20480  NumNegativeBits =
20481  std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20482  }
20483  }
20484 
20485  // If we have an empty set of enumerators we still need one bit.
20486  // From [dcl.enum]p8
20487  // If the enumerator-list is empty, the values of the enumeration are as if
20488  // the enumeration had a single enumerator with value 0
20489  if (!NumPositiveBits && !NumNegativeBits)
20490  NumPositiveBits = 1;
20491 
20492  // Figure out the type that should be used for this enum.
20493  QualType BestType;
20494  unsigned BestWidth;
20495 
20496  // C++0x N3000 [conv.prom]p3:
20497  // An rvalue of an unscoped enumeration type whose underlying
20498  // type is not fixed can be converted to an rvalue of the first
20499  // of the following types that can represent all the values of
20500  // the enumeration: int, unsigned int, long int, unsigned long
20501  // int, long long int, or unsigned long long int.
20502  // C99 6.4.4.3p2:
20503  // An identifier declared as an enumeration constant has type int.
20504  // The C99 rule is modified by a gcc extension
20505  QualType BestPromotionType;
20506 
20507  bool Packed = Enum->hasAttr<PackedAttr>();
20508  // -fshort-enums is the equivalent to specifying the packed attribute on all
20509  // enum definitions.
20510  if (LangOpts.ShortEnums)
20511  Packed = true;
20512 
20513  // If the enum already has a type because it is fixed or dictated by the
20514  // target, promote that type instead of analyzing the enumerators.
20515  if (Enum->isComplete()) {
20516  BestType = Enum->getIntegerType();
20517  if (Context.isPromotableIntegerType(BestType))
20518  BestPromotionType = Context.getPromotedIntegerType(BestType);
20519  else
20520  BestPromotionType = BestType;
20521 
20522  BestWidth = Context.getIntWidth(BestType);
20523  }
20524  else if (NumNegativeBits) {
20525  // If there is a negative value, figure out the smallest integer type (of
20526  // int/long/longlong) that fits.
20527  // If it's packed, check also if it fits a char or a short.
20528  if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20529  BestType = Context.SignedCharTy;
20530  BestWidth = CharWidth;
20531  } else if (Packed && NumNegativeBits <= ShortWidth &&
20532  NumPositiveBits < ShortWidth) {
20533  BestType = Context.ShortTy;
20534  BestWidth = ShortWidth;
20535  } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20536  BestType = Context.IntTy;
20537  BestWidth = IntWidth;
20538  } else {
20539  BestWidth = Context.getTargetInfo().getLongWidth();
20540 
20541  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20542  BestType = Context.LongTy;
20543  } else {
20544  BestWidth = Context.getTargetInfo().getLongLongWidth();
20545 
20546  if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20547  Diag(Enum->getLocation(), diag::ext_enum_too_large);
20548  BestType = Context.LongLongTy;
20549  }
20550  }
20551  BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20552  } else {
20553  // If there is no negative value, figure out the smallest type that fits
20554  // all of the enumerator values.
20555  // If it's packed, check also if it fits a char or a short.
20556  if (Packed && NumPositiveBits <= CharWidth) {
20557  BestType = Context.UnsignedCharTy;
20558  BestPromotionType = Context.IntTy;
20559  BestWidth = CharWidth;
20560  } else if (Packed && NumPositiveBits <= ShortWidth) {
20561  BestType = Context.UnsignedShortTy;
20562  BestPromotionType = Context.IntTy;
20563  BestWidth = ShortWidth;
20564  } else if (NumPositiveBits <= IntWidth) {
20565  BestType = Context.UnsignedIntTy;
20566  BestWidth = IntWidth;
20567  BestPromotionType
20568  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20569  ? Context.UnsignedIntTy : Context.IntTy;
20570  } else if (NumPositiveBits <=
20571  (BestWidth = Context.getTargetInfo().getLongWidth())) {
20572  BestType = Context.UnsignedLongTy;
20573  BestPromotionType
20574  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20575  ? Context.UnsignedLongTy : Context.LongTy;
20576  } else {
20577  BestWidth = Context.getTargetInfo().getLongLongWidth();
20578  if (NumPositiveBits > BestWidth) {
20579  // This can happen with bit-precise integer types, but those are not
20580  // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20581  // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20582  // a 128-bit integer, we should consider doing the same.
20583  Diag(Enum->getLocation(), diag::ext_enum_too_large);
20584  }
20585  BestType = Context.UnsignedLongLongTy;
20586  BestPromotionType
20587  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20588  ? Context.UnsignedLongLongTy : Context.LongLongTy;
20589  }
20590  }
20591 
20592  // Loop over all of the enumerator constants, changing their types to match
20593  // the type of the enum if needed.
20594  for (auto *D : Elements) {
20595  auto *ECD = cast_or_null<EnumConstantDecl>(D);
20596  if (!ECD) continue; // Already issued a diagnostic.
20597 
20598  // Standard C says the enumerators have int type, but we allow, as an
20599  // extension, the enumerators to be larger than int size. If each
20600  // enumerator value fits in an int, type it as an int, otherwise type it the
20601  // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20602  // that X has type 'int', not 'unsigned'.
20603 
20604  // Determine whether the value fits into an int.
20605  llvm::APSInt InitVal = ECD->getInitVal();
20606 
20607  // If it fits into an integer type, force it. Otherwise force it to match
20608  // the enum decl type.
20609  QualType NewTy;
20610  unsigned NewWidth;
20611  bool NewSign;
20612  if (!getLangOpts().CPlusPlus &&
20613  !Enum->isFixed() &&
20614  isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20615  NewTy = Context.IntTy;
20616  NewWidth = IntWidth;
20617  NewSign = true;
20618  } else if (ECD->getType() == BestType) {
20619  // Already the right type!
20620  if (getLangOpts().CPlusPlus)
20621  // C++ [dcl.enum]p4: Following the closing brace of an
20622  // enum-specifier, each enumerator has the type of its
20623  // enumeration.
20624  ECD->setType(EnumType);
20625  continue;
20626  } else {
20627  NewTy = BestType;
20628  NewWidth = BestWidth;
20629  NewSign = BestType->isSignedIntegerOrEnumerationType();
20630  }
20631 
20632  // Adjust the APSInt value.
20633  InitVal = InitVal.extOrTrunc(NewWidth);
20634  InitVal.setIsSigned(NewSign);
20635  ECD->setInitVal(Context, InitVal);
20636 
20637  // Adjust the Expr initializer and type.
20638  if (ECD->getInitExpr() &&
20639  !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20640  ECD->setInitExpr(ImplicitCastExpr::Create(
20641  Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20642  /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20643  if (getLangOpts().CPlusPlus)
20644  // C++ [dcl.enum]p4: Following the closing brace of an
20645  // enum-specifier, each enumerator has the type of its
20646  // enumeration.
20647  ECD->setType(EnumType);
20648  else
20649  ECD->setType(NewTy);
20650  }
20651 
20652  Enum->completeDefinition(BestType, BestPromotionType,
20653  NumPositiveBits, NumNegativeBits);
20654 
20655  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20656 
20657  if (Enum->isClosedFlag()) {
20658  for (Decl *D : Elements) {
20659  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20660  if (!ECD) continue; // Already issued a diagnostic.
20661 
20662  llvm::APSInt InitVal = ECD->getInitVal();
20663  if (InitVal != 0 && !InitVal.isPowerOf2() &&
20664  !IsValueInFlagEnum(Enum, InitVal, true))
20665  Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20666  << ECD << Enum;
20667  }
20668  }
20669 
20670  // Now that the enum type is defined, ensure it's not been underaligned.
20671  if (Enum->hasAttrs())
20672  CheckAlignasUnderalignment(Enum);
20673 }
20674 
20676  SourceLocation StartLoc,
20677  SourceLocation EndLoc) {
20678  StringLiteral *AsmString = cast<StringLiteral>(expr);
20679 
20680  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20681  AsmString, StartLoc,
20682  EndLoc);
20683  CurContext->addDecl(New);
20684  return New;
20685 }
20686 
20688  auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20689  CurContext->addDecl(New);
20690  PushDeclContext(S, New);
20691  PushFunctionScope();
20692  PushCompoundScope(false);
20693  return New;
20694 }
20695 
20697  D->setStmt(Statement);
20698  PopCompoundScope();
20699  PopFunctionScopeInfo();
20700  PopDeclContext();
20701 }
20702 
20704  IdentifierInfo* AliasName,
20705  SourceLocation PragmaLoc,
20706  SourceLocation NameLoc,
20707  SourceLocation AliasNameLoc) {
20708  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20709  LookupOrdinaryName);
20710  AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20712  AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20713  Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20714 
20715  // If a declaration that:
20716  // 1) declares a function or a variable
20717  // 2) has external linkage
20718  // already exists, add a label attribute to it.
20719  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20720  if (isDeclExternC(PrevDecl))
20721  PrevDecl->addAttr(Attr);
20722  else
20723  Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20724  << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20725  // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20726  } else
20727  (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20728 }
20729 
20731  SourceLocation PragmaLoc,
20732  SourceLocation NameLoc) {
20733  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20734 
20735  if (PrevDecl) {
20736  PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20737  } else {
20738  (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20739  }
20740 }
20741 
20743  IdentifierInfo* AliasName,
20744  SourceLocation PragmaLoc,
20745  SourceLocation NameLoc,
20746  SourceLocation AliasNameLoc) {
20747  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20748  LookupOrdinaryName);
20749  WeakInfo W = WeakInfo(Name, NameLoc);
20750 
20751  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20752  if (!PrevDecl->hasAttr<AliasAttr>())
20753  if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20754  DeclApplyPragmaWeak(TUScope, ND, W);
20755  } else {
20756  (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20757  }
20758 }
20759 
20761  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20762 }
20763 
20765  // FIXME: This should really be a bitwise-or of the language modes.
20766  if (FD->hasAttr<SYCLSimdAttr>())
20768  if (FD->hasAttr<SYCLDeviceAttr>() || FD->hasAttr<SYCLKernelAttr>())
20770  // FIXME: Refine the logic for CUDA and OpenMP.
20771  if (getLangOpts().CUDA)
20772  return getLangOpts().CUDAIsDevice ? Sema::DeviceDiagnosticReason::CudaDevice
20774  if (getLangOpts().OpenMP)
20775  return getLangOpts().OpenMPIsTargetDevice
20779 }
20780 
20782  bool Final) {
20783  assert(FD && "Expected non-null FunctionDecl");
20784 
20785  // Templates are emitted when they're instantiated.
20786  if (FD->isDependentContext())
20787  return FunctionEmissionStatus::TemplateDiscarded;
20788 
20789  if (LangOpts.SYCLIsDevice &&
20790  (FD->hasAttr<SYCLDeviceAttr>() || FD->hasAttr<SYCLKernelAttr>()))
20791  return FunctionEmissionStatus::Emitted;
20792 
20793  // Check whether this function is an externally visible definition.
20794  auto IsEmittedForExternalSymbol = [this, FD]() {
20795  // We have to check the GVA linkage of the function's *definition* -- if we
20796  // only have a declaration, we don't know whether or not the function will
20797  // be emitted, because (say) the definition could include "inline".
20798  const FunctionDecl *Def = FD->getDefinition();
20799 
20800  return Def && !isDiscardableGVALinkage(
20801  getASTContext().GetGVALinkageForFunction(Def));
20802  };
20803 
20804  if (LangOpts.OpenMPIsTargetDevice) {
20805  // In OpenMP device mode we will not emit host only functions, or functions
20806  // we don't need due to their linkage.
20807  std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20808  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20809  // DevTy may be changed later by
20810  // #pragma omp declare target to(*) device_type(*).
20811  // Therefore DevTy having no value does not imply host. The emission status
20812  // will be checked again at the end of compilation unit with Final = true.
20813  if (DevTy)
20814  if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20815  return FunctionEmissionStatus::OMPDiscarded;
20816  // If we have an explicit value for the device type, or we are in a target
20817  // declare context, we need to emit all extern and used symbols.
20818  if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20819  if (IsEmittedForExternalSymbol())
20820  return FunctionEmissionStatus::Emitted;
20821  // Device mode only emits what it must, if it wasn't tagged yet and needed,
20822  // we'll omit it.
20823  if (Final)
20824  return FunctionEmissionStatus::OMPDiscarded;
20825  } else if (LangOpts.OpenMP > 45) {
20826  // In OpenMP host compilation prior to 5.0 everything was an emitted host
20827  // function. In 5.0, no_host was introduced which might cause a function to
20828  // be ommitted.
20829  std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20830  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20831  if (DevTy)
20832  if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20833  return FunctionEmissionStatus::OMPDiscarded;
20834  }
20835 
20836  if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20837  return FunctionEmissionStatus::Emitted;
20838 
20839  if (LangOpts.CUDA) {
20840  // When compiling for device, host functions are never emitted. Similarly,
20841  // when compiling for host, device and global functions are never emitted.
20842  // (Technically, we do emit a host-side stub for global functions, but this
20843  // doesn't count for our purposes here.)
20844  CUDAFunctionTarget T = CUDA().IdentifyTarget(FD);
20845  if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20846  return FunctionEmissionStatus::CUDADiscarded;
20847  if (!LangOpts.CUDAIsDevice &&
20849  return FunctionEmissionStatus::CUDADiscarded;
20850 
20851  if (IsEmittedForExternalSymbol())
20852  return FunctionEmissionStatus::Emitted;
20853  }
20854 
20855  if (getLangOpts().SYCLIsDevice) {
20856  if (!FD->hasAttr<SYCLDeviceAttr>() && !FD->hasAttr<SYCLKernelAttr>())
20858 
20859  // Check whether this function is externally visible -- if so, it's
20860  // known-emitted.
20861  //
20862  // We have to check the GVA linkage of the function's *definition* -- if we
20863  // only have a declaration, we don't know whether or not the function will
20864  // be emitted, because (say) the definition could include "inline".
20865  const FunctionDecl *Def = FD->getDefinition();
20866 
20867  if (Def &&
20868  !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)))
20869  return FunctionEmissionStatus::Emitted;
20870  }
20871 
20872  // Otherwise, the function is known-emitted if it's in our set of
20873  // known-emitted functions.
20875 }
20876 
20878  // Host-side references to a __global__ function refer to the stub, so the
20879  // function itself is never emitted and therefore should not be marked.
20880  // If we have host fn calls kernel fn calls host+device, the HD function
20881  // does not get instantiated on the host. We model this by omitting at the
20882  // call to the kernel from the callgraph. This ensures that, when compiling
20883  // for host, only HD functions actually called from the host get marked as
20884  // known-emitted.
20885  return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20886  CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global;
20887 }
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:82
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
llvm::APSInt APSInt
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines helper utilities for supporting the HLSL runtime environment.
unsigned Iter
Definition: HTMLLogger.cpp:154
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition: MachO.h:27
llvm::MachO::Target Target
Definition: MachO.h:48
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:16144
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:7034
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition: SemaDecl.cpp:148
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15650
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11576
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:203
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3504
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
Definition: SemaDecl.cpp:3671
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:816
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6721
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1495
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2383
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9404
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
Definition: SemaDecl.cpp:3618
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2899
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8390
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9753
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3402
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7598
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8776
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11996
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
Definition: SemaDecl.cpp:2788
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4589
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:12102
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15634
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11712
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2091
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15247
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11585
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
Definition: SemaDecl.cpp:7365
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
Definition: SemaDecl.cpp:19929
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:20293
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:5143
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:3085
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:17197
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3653
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7125
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:6098
static bool isDeclExternC(const Decl *D)
Returns true if given declaration has external C language linkage.
Definition: SemaDecl.cpp:7480
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
Definition: SemaDecl.cpp:5013
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:16173
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8745
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2757
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9625
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3200
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8415
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:17361
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
Definition: SemaDecl.cpp:5428
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
Definition: SemaDecl.cpp:8662
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1967
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9947
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
Definition: SemaDecl.cpp:5508
OpenCLParamType
Definition: SemaDecl.cpp:9616
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9620
@ ValidKernelParam
Definition: SemaDecl.cpp:9617
@ InvalidKernelParam
Definition: SemaDecl.cpp:9621
@ RecordKernelParam
Definition: SemaDecl.cpp:9622
@ PtrKernelParam
Definition: SemaDecl.cpp:9619
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9618
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
Definition: SemaDecl.cpp:6207
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
Definition: SemaDecl.cpp:19287
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:583
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
Definition: SemaDecl.cpp:19221
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7410
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5592
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11505
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3465
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3597
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:17181
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2220
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4479
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:6133
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
Definition: SemaDecl.cpp:19314
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:831
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7437
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8379
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8386
@ SDK_Field
Definition: SemaDecl.cpp:8383
@ SDK_Global
Definition: SemaDecl.cpp:8381
@ SDK_Local
Definition: SemaDecl.cpp:8380
@ SDK_Typedef
Definition: SemaDecl.cpp:8384
@ SDK_StaticMember
Definition: SemaDecl.cpp:8382
@ SDK_Using
Definition: SemaDecl.cpp:8385
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3560
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4959
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:563
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3581
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
Definition: SemaDecl.cpp:19052
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:9253
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9647
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5606
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12725
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6759
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:11165
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7490
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1824
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:19380
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11334
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1813
static void filterNonConflictingPreviousTypedefDecls(Sema &S, TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
Definition: SemaDecl.cpp:2506
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6643
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:15051
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7586
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:6080
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11601
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1878
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11284
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6995
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5571
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:245
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:9927
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
Definition: SemaDecl.cpp:11743
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
Definition: SemaDecl.cpp:8406
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9440
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
Definition: SemaDecl.cpp:11551
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:3059
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7216
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
Definition: SemaDecl.cpp:9936
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11349
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:20257
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19946
static bool isExternC(T *D)
Definition: SemaDecl.cpp:3610
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7396
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2776
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1840
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
Definition: SemaDecl.cpp:17398
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for OpenMP constructs and clauses.
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
This file declares semantic analysis for SYCL constructs.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
SourceLocation End
StateNode * Previous
std::string Label
__DEVICE__ int max(int __a, int __b)
__device__ int
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:16131
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:16133
llvm::APInt getValue() const
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
QualType getParenType(QualType NamedType) const
SourceManager & getSourceManager()
Definition: ASTContext.h:705
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2767
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2089
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1875
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2568
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2584
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1979
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1901
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1957
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1594
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2761
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:496
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2764
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2077
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1991
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2160
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1100
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2067
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2611
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2334
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1572
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1424
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1100
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1888
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2183
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1967
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1100
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2236
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2242
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2239
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2248
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2245
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2365
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3098
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1563
Expr * getSizeExpr() const
Definition: TypeLoc.h:1583
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1571
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3318
QualType getElementType() const
Definition: Type.h:3330
Attr - This represents one attribute.
Definition: Attr.h:46
Attr * clone(ASTContext &C) const
attr::Kind getKind() const
Definition: Attr.h:92
bool isInherited() const
Definition: Attr.h:101
void setImplicit(bool I)
Definition: Attr.h:106
SourceLocation getLocation() const
Definition: Attr.h:99
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:634
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:730
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5404
QualType getModifiedType() const
Definition: Type.h:5426
bool isCallingConv() const
Definition: Type.cpp:4070
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5459
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5781
AutoTypeKeyword getKeyword() const
Definition: Type.h:5812
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4293
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4347
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition: Expr.h:4335
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3892
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:4032
Expr * getRHS() const
Definition: Expr.h:3943
Expr * getLHS() const
Definition: Expr.h:3941
A binding in a decomposition declaration.
Definition: DeclCXX.h:4104
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
bool doesNotEscape() const
Definition: Decl.h:4647
This class is used for builtin types like 'int'.
Definition: Type.h:2777
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:209
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:137
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:247
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:202
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:167
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:204
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:199
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:222
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:251
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:174
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:116
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:122
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:195
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1683
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2532
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2760
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2721
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2859
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2888
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition: DeclCXX.cpp:2156
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2796
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2855
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2453
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2507
bool isVirtual() const
Definition: DeclCXX.h:2112
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2183
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2574
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2486
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2273
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2218
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2153
bool isConst() const
Definition: DeclCXX.h:2109
bool isStatic() const
Definition: DeclCXX.cpp:2185
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2464
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1334
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1240
base_class_iterator bases_end()
Definition: DeclCXX.h:627
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1547
base_class_range bases()
Definition: DeclCXX.h:618
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1376
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1929
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition: DeclCXX.h:625
capture_const_range captures() const
Definition: DeclCXX.h:1100
bool hasDefinition() const
Definition: DeclCXX.h:571
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1896
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1062
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1900
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1288
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:235
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
bool isCallToStdMove() const
Definition: Expr.cpp:3562
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3063
arg_range arguments()
Definition: Expr.h:3111
Expr * getCallee()
Definition: Expr.h:3022
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3579
Expr * getSubExpr()
Definition: Expr.h:3585
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4231
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:178
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:218
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3412
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1371
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2344
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1438
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2193
bool isFileContext() const
Definition: DeclBase.h:2139
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1975
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2068
bool isClosure() const
Definition: DeclBase.h:2101
bool isNamespace() const
Definition: DeclBase.h:2153
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1231
bool isTranslationUnit() const
Definition: DeclBase.h:2144
bool isRecord() const
Definition: DeclBase.h:2148
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2084
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1617
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1567
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1938
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1354
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2324
bool isFunctionOrMethod() const
Definition: DeclBase.h:2120
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1215
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2061
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1345
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:825
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:308
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:591
static const TST TST_typename
Definition: DeclSpec.h:305
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:641
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
bool isNoreturnSpecified() const
Definition: DeclSpec.h:657
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:856
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:705
static const TST TST_interface
Definition: DeclSpec.h:303
static const TST TST_typeofExpr
Definition: DeclSpec.h:307
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:612
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:704
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:658
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:501
static const TST TST_union
Definition: DeclSpec.h:301
SCS
storage-class-specifier
Definition: DeclSpec.h:250
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
static const TST TST_int
Definition: DeclSpec.h:284
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:826
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1494
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:784
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:622
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:613
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:651
static const TST TST_enum
Definition: DeclSpec.h:300
static const TST TST_decltype
Definition: DeclSpec.h:310
static bool isDeclRep(TST T)
Definition: DeclSpec.h:465
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:614
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:309
static const TST TST_class
Definition: DeclSpec.h:304
void ClearConstexprSpec()
Definition: DeclSpec.h:837
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_atomic
Definition: DeclSpec.h:320
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:277
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:616
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:788
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:266
static const TST TST_error
Definition: DeclSpec.h:324
ExplicitSpecifier getExplicitSpecifier() const
Definition: DeclSpec.h:640
bool isTypeSpecOwned() const
Definition: DeclSpec.h:537
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:617
Decl * getRepAsDecl() const
Definition: DeclSpec.h:547
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:615
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:817
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
static const TST TST_typeofType
Definition: DeclSpec.h:306
static const TST TST_auto
Definition: DeclSpec.h:317
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:828
static const TST TST_struct
Definition: DeclSpec.h:302
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:295
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1218
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1111
bool hasAttrs() const
Definition: DeclBase.h:526
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:601
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:528
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:756
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1143
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:640
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:885
AttrVec & getAttrs()
Definition: DeclBase.h:532
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1211
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1209
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1210
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1074
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:555
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1105
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
void dropAttrs()
Definition: DeclBase.cpp:968
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:209
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1172
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2741
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1053
bool isInvalidDecl() const
Definition: DeclBase.h:596
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:970
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1161
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:510
SourceLocation getLocation() const
Definition: DeclBase.h:447
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:567
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:143
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:910
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:602
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:616
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1068
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
attr_range attrs() const
Definition: DeclBase.h:543
AccessSpecifier getAccess() const
Definition: DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:439
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:830
void dropAttr()
Definition: DeclBase.h:564
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
bool hasAttr() const
Definition: DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1227
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
Kind getKind() const
Definition: DeclBase.h:450
T * getAttr() const
Definition: DeclBase.h:581
DeclContext * getDeclContext()
Definition: DeclBase.h:456
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:771
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:847
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:814
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2051
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:829
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2091
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1989
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:859
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:806
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2001
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2035
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2454
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2052
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2631
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2739
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2762
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2334
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2337
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2060
Expr * getAsmLabel() const
Definition: DeclSpec.h:2700
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2082
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2711
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2684
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2392
bool isRedeclaration() const
Definition: DeclSpec.h:2763
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:436
bool isFunctionDefinition() const
Definition: DeclSpec.h:2735
bool hasInitializer() const
Definition: DeclSpec.h:2744
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2731
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2485
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2674
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2064
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2351
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2681
bool isInvalidType() const
Definition: DeclSpec.h:2712
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:424
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2066
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2324
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition: DeclSpec.h:2661
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2747
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2396
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
A decomposition declaration.
Definition: DeclCXX.h:4163
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3354
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1788
SourceRange getSourceRange() const
Definition: DeclSpec.h:1834
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1832
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5747
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5768
bool isDeduced() const
Definition: Type.h:5769
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:922
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3299
const Expr * getInitExpr() const
Definition: Decl.h:3317
llvm::APSInt getInitVal() const
Definition: Decl.h:3319
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5458
Represents an enum.
Definition: Decl.h:3869
enumerator_range enumerators() const
Definition: Decl.h:4002
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4074
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4038
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4041
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4088
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4858
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4903
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4083
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4878
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4024
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4029
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5375
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1896
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3107
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3091
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:949
bool isFPConstrained() const
Definition: LangOptions.h:877
Represents a member of a struct/union/class.
Definition: Decl.h:3059
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3150
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4566
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4603
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4551
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3272
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5590
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
Represents a function declaration or definition.
Definition: Decl.h:1972
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2601
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2440
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4058
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3607
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4051
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4046
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3259
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2285
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2613
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2592
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3877
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3636
param_iterator param_end()
Definition: Decl.h:2698
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2832
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2607
QualType getReturnType() const
Definition: Decl.h:2756
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3580
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2353
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2341
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3492
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4166
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2412
void setWillHaveBody(bool V=true)
Definition: Decl.h:2598
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2407
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4176
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3621
param_iterator param_begin()
Definition: Decl.h:2697
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3093
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2297
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2504
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3318
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4110
@ TK_MemberSpecialization
Definition: Decl.h:1984
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2799
bool isStatic() const
Definition: Decl.h:2840
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4378
void setTrivial(bool IT)
Definition: Decl.h:2342
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3997
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2434
bool isDeletedAsWritten() const
Definition: Decl.h:2508
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2429
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2324
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2162
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3496
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2328
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2392
bool isImmediateEscalating() const
Definition: Decl.cpp:3272
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2320
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2591
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3310
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2827
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3370
bool param_empty() const
Definition: Decl.h:2696
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3184
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2191
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3576
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2349
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2734
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2385
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4401
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2844
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2685
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3991
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3983
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2437
void setDefaulted(bool D=true)
Definition: Decl.h:2350
bool isConsteval() const
Definition: Decl.h:2446
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2773
void setBody(Stmt *B)
Definition: Decl.cpp:3252
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3510
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3130
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2423
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4018
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2184
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3160
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2253
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2399
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3207
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2810
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3562
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2597
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2708
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4456
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4696
ArrayRef< QualType > param_types() const
Definition: Type.h:4844
unsigned getNumParams() const
Definition: Type.h:4689
QualType getParamType(unsigned i) const
Definition: Type.h:4691
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4721
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4812
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4700
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:523
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:537
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4167
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4282
CallingConv getCC() const
Definition: Type.h:4229
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4248
unsigned getRegParm() const
Definition: Type.h:4222
bool getNoCallerSavedRegs() const
Definition: Type.h:4218
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4241
bool getHasRegParm() const
Definition: Type.h:4220
bool getNoReturn() const
Definition: Type.h:4215
bool getProducesResult() const
Definition: Type.h:4216
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4262
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4276
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4056
ExtInfo getExtInfo() const
Definition: Type.h:4385
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3476
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4343
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4339
unsigned getRegParmType() const
Definition: Type.h:4376
CallingConv getCallConv() const
Definition: Type.h:4384
QualType getReturnType() const
Definition: Type.h:4373
bool getCmseNSCallAttr() const
Definition: Type.h:4383
@ SME_PStateSMEnabledMask
Definition: Type.h:4317
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3707
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2129
Represents a C array with an unspecified size.
Definition: Type.h:3503
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3343
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5486
void setInherited(bool I)
Definition: Attr.h:158
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2503
Describes an C or C++ initializer list.
Definition: Expr.h:4888
child_range children()
Definition: Expr.h:5080
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8592
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
Represents the declaration of a label.
Definition: Decl.h:500
bool isResolvedMSAsmLabel() const
Definition: Decl.h:535
LabelStmt * getStmt() const
Definition: Decl.h:524
bool isMSAsmLabel() const
Definition: Decl.h:534
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:282
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:475
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:659
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:692
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:510
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:567
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:698
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:549
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1358
Represents a linkage specification.
Definition: DeclCXX.h:2931
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2918
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:673
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:719
NamedDecl * next()
Definition: Lookup.h:708
bool hasNext() const
Definition: Lookup.h:704
Represents the results of name lookup.
Definition: Lookup.h:46
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:573
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
DeclClass * getAsSingle() const
Definition: Lookup.h:556
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:662
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:747
bool isAmbiguous() const
Definition: Lookup.h:324
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:668
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3224
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3307
Expr * getBase() const
Definition: Expr.h:3301
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3260
Describes a module or submodule.
Definition: Module.h:105
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
Module * Parent
The parent of this module.
Definition: Module.h:154
bool isPrivateModule() const
Definition: Module.h:210
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:591
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:607
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:630
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:596
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:665
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:249
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1072
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:420
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:455
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:405
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:463
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1854
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:688
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1931
bool isExternallyVisible() const
Definition: Decl.h:409
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1119
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:373
Represent a C++ namespace.
Definition: Decl.h:548
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:606
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2323
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2767
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:946
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:81
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2590
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1539
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1758
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1948
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1832
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
bool isOptional() const
Definition: DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
Expr ** getExprs()
Definition: Expr.h:5705
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5694
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1216
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Sugar for parentheses used when specifying types.
Definition: Type.h:2913
Represents a parameter to a function.
Definition: Decl.h:1762
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1822
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1826
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1795
QualType getOriginalType() const
Definition: Decl.cpp:2928
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2919
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:831
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:911
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:951
AttributePool & getPool() const
Definition: ParsedAttr.h:957
PipeType - OpenCL20.
Definition: Type.h:7008
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1282
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2939
QualType getPointeeType() const
Definition: Type.h:2949
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7243
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7237
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:7306
@ DK_nontrivial_c_struct
Definition: Type.h:1317
PrimitiveDefaultInitializeKind
Definition: Type.h:1245
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2810
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1007
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1089
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2858
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7159
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7285
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:898
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:7300
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7199
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
QualType getCanonicalType() const
Definition: Type.h:7211
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7253
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2842
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1225
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7232
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1324
bool isCanonical() const
Definition: Type.h:7216
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1102
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1125
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1234
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2561
NonConstantStorageReason
Definition: Type.h:822
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1275
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1280
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:7294
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7099
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7106
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4278
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:176
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:169
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:165
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:182
bool hasConst() const
Definition: Type.h:265
void removeConst()
Definition: Type.h:267
void addConst()
Definition: Type.h:268
ObjCLifetime getObjCLifetime() const
Definition: Type.h:353
bool empty() const
Definition: Type.h:441
Represents a struct/union/class.
Definition: Decl.h:4170
bool hasObjectMember() const
Definition: Decl.h:4230
field_range fields() const
Definition: Decl.h:4376
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4361
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5021
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5040
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5086
field_iterator field_begin() const
Definition: Decl.cpp:5074
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5349
RecordDecl * getDecl() const
Definition: Type.h:5359
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6681
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:866
redecl_iterator redecls_end() const
Definition: Redeclarable.h:303
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4996
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:223
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3180
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3067
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:378
void RemoveDecl(Decl *D)
Definition: Scope.h:350
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:381
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:578
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:267
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
DeviceDiagnosticReason
Bitmask to contain the list of reasons a single diagnostic should be emitted, based on its language.
Definition: SemaBase.h:99
@ Sycl
SYCL specific diagnostic.
@ CudaDevice
CUDA specific diagnostics.
@ Esimd
ESIMD specific diagnostic.
@ All
A flag representing 'all'.
@ OmpDevice
OpenMP specific diagnostic.
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:48
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
Definition: SemaHLSL.cpp:63
@ KernelNonConstStaticDataVariable
Definition: SemaSYCL.h:302
bool IsAlignAttr() const
Definition: Sema.h:1263
Mode getAlignMode() const
Definition: Sema.h:1265
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2552
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:938
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:950
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9701
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9731
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:458
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14501
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:11200
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6820
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6886
void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl)
Definition: SemaDecl.cpp:18449
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2584
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:6804
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2545
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9974
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:522
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1584
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
SYCLIntelMaxConcurrencyAttr * MergeSYCLIntelMaxConcurrencyAttr(Decl *D, const SYCLIntelMaxConcurrencyAttr &A)
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15394
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7541
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7545
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:7564
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7580
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7553
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7548
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6822
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2236
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5461
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:16115
SYCLIntelMaxReplicatesAttr * MergeSYCLIntelMaxReplicatesAttr(Decl *D, const SYCLIntelMaxReplicatesAttr &A)
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13143
NonTrivialCUnionContext
Definition: Sema.h:3006
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
Definition: SemaDecl.cpp:3722
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:6291
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18572
SYCLIntelNumSimdWorkItemsAttr * MergeSYCLIntelNumSimdWorkItemsAttr(Decl *D, const SYCLIntelNumSimdWorkItemsAttr &A)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6258
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:826
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18497
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:3513
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16656
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15271
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1479
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7084
IntelNamedSubGroupSizeAttr * MergeIntelNamedSubGroupSizeAttr(Decl *D, const IntelNamedSubGroupSizeAttr &A)
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1414
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6419
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4965
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
Definition: SemaDecl.cpp:12565
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16872
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2155
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
Definition: SemaDecl.cpp:18591
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:18691
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14879
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1455
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15757
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3589
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:647
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1690
SYCLIntelLoopFuseAttr * MergeSYCLIntelLoopFuseAttr(Decl *D, const SYCLIntelLoopFuseAttr &A)
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:20675
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15381
ASTContext & Context
Definition: Sema.h:859
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14901
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5957
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20696
void * SkippedDefinitionContext
Definition: Sema.h:3254
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5470
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:5075
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:67
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1522
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2441
void CheckCoroutineWrapper(FunctionDecl *FD)
Definition: SemaDecl.cpp:16187
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Definition: SemaDecl.cpp:1755
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:18165
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:685
SYCLAddIRAttributesGlobalVariableAttr * MergeSYCLAddIRAttributesGlobalVariableAttr(Decl *D, const SYCLAddIRAttributesGlobalVariableAttr &A)
SYCLDeviceHasAttr * MergeSYCLDeviceHasAttr(Decl *D, const SYCLDeviceHasAttr &A)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4920
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20877
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5627
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:17232
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9240
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4502
SYCLAddIRAttributesFunctionAttr * MergeSYCLAddIRAttributesFunctionAttr(Decl *D, const SYCLAddIRAttributesFunctionAttr &A)
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
Definition: SemaDecl.cpp:1268
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ObjCInterfaceDecl * getObjCInterfaceDecl(const IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:2326
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:3400
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:17125
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:20151
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
SYCLIntelPipeIOAttr * MergeSYCLIntelPipeIOAttr(Decl *D, const SYCLIntelPipeIOAttr &A)
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1412
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6776
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
Definition: SemaDecl.cpp:6814
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1627
Preprocessor & PP
Definition: Sema.h:858
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8443
DeviceDiagnosticReason getEmissionReason(const FunctionDecl *Decl)
Definition: SemaDecl.cpp:20764
const LangOptions & LangOpts
Definition: Sema.h:857
const LangOptions & getLangOpts() const
Definition: Sema.h:521
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2460
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15600
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1884
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:12145
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:18796
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:16073
SYCLAddIRAnnotationsMemberAttr * MergeSYCLAddIRAnnotationsMemberAttr(Decl *D, const SYCLAddIRAnnotationsMemberAttr &A)
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9853
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:880
IntelReqdSubGroupSizeAttr * MergeIntelReqdSubGroupSizeAttr(Decl *D, const IntelReqdSubGroupSizeAttr &A)
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:17203
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1399
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8595
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12744
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:20177
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:15133
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2400
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2375
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20730
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18986
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:18455
SYCLAddIRAttributesKernelParameterAttr * MergeSYCLAddIRAttributesKernelParameterAttr(Decl *D, const SYCLAddIRAttributesKernelParameterAttr &A)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:9113
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11925
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20781
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
Definition: SemaDecl.cpp:9135
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15703
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18440
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15630
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:997
SYCLIntelESimdVectorizeAttr * MergeSYCLIntelESimdVectorizeAttr(Decl *D, const SYCLIntelESimdVectorizeAttr &A)
SYCLIntelSchedulerTargetFmaxMhzAttr * MergeSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const SYCLIntelSchedulerTargetFmaxMhzAttr &A)
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15173
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5963
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15467
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
SYCLTypeAttr * MergeSYCLTypeAttr(Decl *D, const AttributeCommonInfo &CI, SYCLTypeAttr::SYCLType TypeName)
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8637
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1310
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4863
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:16036
ObjCContainerDecl * getObjCDeclContext() const
Definition: SemaDecl.cpp:20760
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:16097
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
Definition: SemaDecl.cpp:11220
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3169
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:18556
SYCLWorkGroupSizeHintAttr * MergeSYCLWorkGroupSizeHintAttr(Decl *D, const SYCLWorkGroupSizeHintAttr &A)
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4420
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20432
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1364
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
Definition: SemaDecl.cpp:11392
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18426
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20571
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:16125
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:14115
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
Definition: SemaDecl.cpp:1249
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
SYCLIntelMaxGlobalWorkDimAttr * MergeSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const SYCLIntelMaxGlobalWorkDimAttr &A)
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:20703
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
Definition: SemaDecl.cpp:20687
SemaHLSL & HLSL()
Definition: Sema.h:1004
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8477
SYCLIntelNumBanksAttr * MergeSYCLIntelNumBanksAttr(Decl *D, const SYCLIntelNumBanksAttr &A)
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx)
Definition: SemaDecl.cpp:18567
@ CTK_ErrorRecovery
Definition: Sema.h:7774
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14530
SYCLIntelMaxWorkGroupSizeAttr * MergeSYCLIntelMaxWorkGroupSizeAttr(Decl *D, const SYCLIntelMaxWorkGroupSizeAttr &A)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15056
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4626
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:593
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:19179
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3253
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1947
ASTContext & getASTContext() const
Definition: Sema.h:528
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:291
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19970
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12779
ASTConsumer & Consumer
Definition: Sema.h:860
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3432
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2104
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16794
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:7040
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:3354
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:3362
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:3365
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:3368
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15177
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14842
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17426
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4945
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15552
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1357
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19425
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:11253
FPOptions & getCurFPFeatures()
Definition: Sema.h:523
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1329
SourceManager & SourceMgr
Definition: Sema.h:862
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5913
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16182
DiagnosticsEngine & Diags
Definition: Sema.h:861
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16178
QualType AdjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo)
Definition: SemaDecl.cpp:15436
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6839
SYCLIntelMaxWorkGroupsPerMultiprocessorAttr * MergeSYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Decl *D, const SYCLIntelMaxWorkGroupsPerMultiprocessorAttr &A)
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7457
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:15210
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6926
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16641
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2122
void PopDeclContext()
Definition: SemaDecl.cpp:1336
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
SYCLUsesAspectsAttr * MergeSYCLUsesAspectsAttr(Decl *D, const SYCLUsesAspectsAttr &A)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1606
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14157
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13325
SYCLIntelForcePow2DepthAttr * MergeSYCLIntelForcePow2DepthAttr(Decl *D, const SYCLIntelForcePow2DepthAttr &A)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1589
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:17068
SYCLIntelBankWidthAttr * MergeSYCLIntelBankWidthAttr(Decl *D, const SYCLIntelBankWidthAttr &A)
OffsetOfKind
Definition: Sema.h:3196
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13601
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:18681
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4456
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:14447
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6225
SYCLIntelMinWorkGroupsPerComputeUnitAttr * MergeSYCLIntelMinWorkGroupsPerComputeUnitAttr(Decl *D, const SYCLIntelMinWorkGroupsPerComputeUnitAttr &A)
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1729
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
Definition: SemaDecl.cpp:1258
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20742
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8808
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
Definition: SemaDecl.cpp:19064
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1343
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13291
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
SYCLIntelInitiationIntervalAttr * MergeSYCLIntelInitiationIntervalAttr(Decl *D, const SYCLIntelInitiationIntervalAttr &A)
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3237
SYCLReqdWorkGroupSizeAttr * MergeSYCLReqdWorkGroupSizeAttr(Decl *D, const SYCLReqdWorkGroupSizeAttr &A)
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:16062
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:13577
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:20403
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:701
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
Definition: SemaDecl.cpp:15410
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:6615
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition: Sema.h:2888
SYCLIntelNoGlobalWorkOffsetAttr * MergeSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const SYCLIntelNoGlobalWorkOffsetAttr &A)
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6212
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:17144
void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:18561
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7625
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1285
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1926
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3586
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3709
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3684
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3670
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3689
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4743
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4734
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4726
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3861
bool isUnion() const
Definition: Decl.h:3792
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4789
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4826
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3810
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3727
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3814
TagKind getTagKind() const
Definition: Decl.h:3781
void setBraceRange(SourceRange R)
Definition: Decl.h:3666
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Exposes information about the current target.
Definition: TargetInfo.h:213
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1497
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:496
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:504
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1776
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:514
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1540
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1548
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1483
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1372
unsigned getCharWidth() const
Definition: TargetInfo.h:491
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:572
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:509
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1462
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1273
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1451
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:663
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5889
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4200
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
A declaration that models statements at global scope.
Definition: Decl.h:4459
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5605
void setStmt(Stmt *S)
Definition: Decl.cpp:5625
Represents a declaration of a type.
Definition: Decl.h:3392
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3417
const Type * getTypeForDecl() const
Definition: Decl.h:3416
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:751
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7130
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7141
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6152
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3121
The base class of the type hierarchy.
Definition: Type.h:1607
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2454
bool isStructureType() const
Definition: Type.cpp:628
bool isDecltypeType() const
Definition: Type.h:7599
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isDependentSizedArrayType() const
Definition: Type.h:7498
bool isBlockPointerType() const
Definition: Type.h:7420
bool isVoidType() const
Definition: Type.h:7723
bool isBooleanType() const
Definition: Type.h:7851
bool isFunctionReferenceType() const
Definition: Type.h:7453
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7898
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2880
bool isIncompleteArrayType() const
Definition: Type.h:7486
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8017
bool isDependentAddressSpaceType() const
Definition: Type.h:7540
bool isConstantArrayType() const
Definition: Type.h:7482
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7878
bool isVoidPointerType() const
Definition: Type.cpp:654
bool isArrayType() const
Definition: Type.h:7478
bool isFunctionPointerType() const
Definition: Type.h:7446
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2554
bool isPointerType() const
Definition: Type.h:7412
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8008
bool isReferenceType() const
Definition: Type.h:7424
bool isEnumeralType() const
Definition: Type.h:7510
bool isScalarType() const
Definition: Type.h:7822
bool isVariableArrayType() const
Definition: Type.h:7490
bool isClkEventT() const
Definition: Type.h:7625
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7838
bool isSampledImageType() const
Definition: Type.h:7644
bool isImageType() const
Definition: Type.h:7637
bool isPipeType() const
Definition: Type.h:7654
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2457
bool isBitIntType() const
Definition: Type.h:7658
bool isOpenCLSpecificType() const
Definition: Type.h:7683
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2449
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2326
bool isHalfType() const
Definition: Type.h:7727
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1999
const RecordType * getAsStructureType() const
Definition: Type.cpp:710
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2443
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7891
bool isAtomicType() const
Definition: Type.h:7557
bool isFunctionProtoType() const
Definition: Type.h:2284
bool isObjCIdType() const
Definition: Type.h:7577
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2467
bool isObjCObjectType() const
Definition: Type.h:7548
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4893
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7857
bool isEventT() const
Definition: Type.h:7621
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4836
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:7958
bool isFunctionType() const
Definition: Type.h:7408
bool isObjCObjectPointerType() const
Definition: Type.h:7544
bool isMemberFunctionPointerType() const
Definition: Type.h:7464
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
bool isFloatingType() const
Definition: Type.cpp:2237
bool isAnyPointerType() const
Definition: Type.h:7416
TypeClass getTypeClass() const
Definition: Type.h:2094
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2004
bool isSamplerT() const
Definition: Type.h:7617
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7941
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7756
bool isRecordType() const
Definition: Type.h:7506
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4616
bool isUnionType() const
Definition: Type.cpp:660
bool isFunctionNoProtoType() const
Definition: Type.h:2283
bool isReserveIDT() const
Definition: Type.h:7633
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1878
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2456
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1874
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3536
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5508
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3434
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3500
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3484
QualType getUnderlyingType() const
Definition: Decl.h:3489
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3496
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5517
QualType desugar() const
Definition: Type.cpp:3819
TypedefNameDecl * getDecl() const
Definition: Type.h:5017
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
decl_iterator end()
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2235
Opcode getOpcode() const
Definition: Expr.h:2275
Expr * getSubExpr() const
Definition: Expr.h:2280
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2335
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1233
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1082
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3317
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3381
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3110
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
void setType(QualType newType)
Definition: Decl.h:719
QualType getType() const
Definition: Decl.h:718
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5376
Represents a variable declaration or definition.
Definition: Decl.h:919
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2791
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2152
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1506
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1550
TLSKind getTLSKind() const
Definition: Decl.cpp:2169
bool hasInit() const
Definition: Decl.cpp:2399
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1433
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2261
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2191
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2442
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2258
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1559
bool isCXXCondDecl() const
Definition: Decl.h:1596
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:930
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:933
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:927
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2164
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1578
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1271
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1214
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2367
void setInlineSpecified()
Definition: Decl.h:1539
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1196
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1330
const Expr * getInit() const
Definition: Decl.h:1356
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1161
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1532
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1165
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1205
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1172
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2427
void setConstexpr(bool IC)
Definition: Decl.h:1553
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:942
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:945
void setInit(Expr *I)
Definition: Decl.cpp:2458
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2346
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1286
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1283
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1289
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2796
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2246
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1241
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1156
void setImplicitlyInline()
Definition: Decl.h:1544
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1457
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1573
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2687
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1250
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2760
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1467
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2667
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3547
Expr * getSizeExpr() const
Definition: Type.h:3566
Captures information about a #pragma weak directive.
Definition: Weak.h:25
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:141
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:875
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
static constexpr Variable var(Literal L)
Returns the variable of L.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:65
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:52
llvm::APInt APInt
Definition: Integral.h:29
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:217
bool Init(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1461
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:175
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:158
std::string toString(const til::SExpr *E)
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
llvm::cl::opt< std::string > Filter
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_struct
Definition: Specifiers.h:81
@ TST_class
Definition: Specifiers.h:82
@ TST_union
Definition: Specifiers.h:80
@ TST_enum
Definition: Specifiers.h:79
@ TST_interface
Definition: Specifiers.h:83
ImplicitTypenameContext
Definition: DeclSpec.h:1881
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ GNUMode
Definition: LangStandard.h:63
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ GVA_AvailableExternally
Definition: Linkage.h:74
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:28
CUDAFunctionTarget
Definition: Cuda.h:131
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:268
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:44
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Auto
Definition: Specifiers.h:253
@ SC_PrivateExtern
Definition: Specifiers.h:250
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:238
@ TSCS_unspecified
Definition: Specifiers.h:233
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:241
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:235
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:304
TagTypeKind
The kind of a tag type.
Definition: Type.h:6099
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:109
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1548
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1072
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:31
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:432
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
@ LCD_ByRef
Definition: Lambda.h:25
@ LCD_None
Definition: Lambda.h:23
@ LCD_ByCopy
Definition: Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1951
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1277
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:374
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_X86StdCall
Definition: Specifiers.h:277
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
unsigned long uint64_t
#define bool
Definition: stdbool.h:20
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1424
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1399
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1358
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1575
const IdentifierInfo * Ident
Definition: DeclSpec.h:1330
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1640
enum clang::DeclaratorChunk::@219 Kind
FunctionTypeInfo Fun
Definition: DeclSpec.h:1638
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1683
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1659
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:4535
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:4554
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:56
std::vector< std::string > Features
Definition: TargetInfo.h:57
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
bool CheckSameAsPrevious
Definition: Sema.h:360
NamedDecl * Previous
Definition: Sema.h:361
NamedDecl * New
Definition: Sema.h:362
Information about a template-id annotation token.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.